使用 Unity3d 打包 iOS 9 應用時,NGUI 的文字有可能出現中文亂碼。這個問題的根源,往往是 Arial 字型在 iOS 上的渲染異常。以下分享一個有效的解法。
亂碼通常來自 NGUI 的 Label 使用了 Arial 字型,而 Arial 在 iOS 平台上對中文的支援不佳。要修復它,最簡單的辦法就是批量把 Label 的字型改成支援中文的字型(例如微軟雅黑 yahei),並移除 Arial 造成的干擾。
我們可以透過一個編輯器腳本,批次遍歷專案中所有 NGUI Label,把它們的 bitmapFont 替換成指定的中文字型。核心程式碼如下:
static public void yaheifont() {
uf = AssetDatabase.LoadAssetAtPath("Assets/yahei.prefab", typeof(UIFont)) as UIFont;
UnityEngine.Object[] objs = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets);
foreach (UnityEngine.Object _obj in objs) {
string path = AssetDatabase.GetAssetPath(_obj);
Debug.Log("objname:" + _obj.name);
UnityEngine.Object[] arr = AssetDatabase.LoadAllAssetsAtPath(path);
Debug.Log("PATH:" + path);
foreach (Object j in arr) {
if (j.GetType() == typeof(UILabel)) {
(j as UILabel).bitmapFont = uf;
Debug.Log("dfdfd:" + j.name + ",tyep:" + j.GetType());
}
}
EditorUtility.SetDirty(_obj);
}
AssetDatabase.SaveAssets();
}
這段腳本會載入指定的中文字型,遍歷選取的所有資源,把其中的 UILabel 字型替換掉,最後儲存資源。執行後重新打包,中文即可正常顯示。
使用這個方法前,請先確認專案裡已經準備好支援中文的字型檔(例如 yahei.prefab),並依實際路徑調整腳本中的字型載入路徑,就能一勞永逸地解決 iOS 9 上的中文亂碼困擾。