遊戲開發過程當中,根據策劃需求常常會有多語言功能,最簡單的實現方法即爲將遊戲中全部的文字配置在一張數據表中,而後根據需求動態的加載配置表。在UI拼接過程當中,常常會有一些文字是固定不變的,那麼就須要將這些字放入數據表中,而後策劃或他人根據此數據表將文字翻譯爲其它語言。以下圖(須要將選中的文字進行配置):ide
本人開發過程當中,習慣於每一個固定不變的文字(Text或Label)上面掛載一腳本,在Awake或者Start方法中根據數據表內容設置文字信息。可是在UI拼接過程當中,根據美術提供的UI每次手動的將對應的文字輸入到UI位置(Text或Label),將文字對應的key輸入到掛載腳本位置,而後再將文字以及key配置到Excel中,顯得很是麻煩,因此作了一小工具以下圖,配置文字key,點擊InsertToExcel按鈕,將key以及文字配置到配置表中。工具
UILocalization.cs腳本以下:ui
using System; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Text))] public class UILocalization : MonoBehaviour { [SerializeField] private string _localizationKey; void Start() { if (string.IsNullOrEmpty(_localizationKey)) { throw new Exception(string.Format("Text:{0} key is null", gameObject.name)); } Text text = GetComponent<Text>(); //寫入給text賦值代碼便可 //text.text = GameEntry.Localization.GetString(_localizationKey); } }
UILocalizationInspector.cs腳本以下:spa
using System.Diagnostics; using UnityEditor; using UnityEngine; using System.IO; using UnityEngine.UI; [CustomEditor(typeof(UILocalization))] public class UILocalizationInspector : UnityEditor.Editor { private SerializedObject _object; private SerializedProperty _languageKey; private Text _textLanguage; public void OnEnable() { _object = new SerializedObject(target); _languageKey = _object.FindProperty("_localizationKey"); _textLanguage = ((_object.targetObject) as UILocalization).GetComponent<Text>(); } public override void OnInspectorGUI() { _object.Update(); EditorGUILayout.PropertyField(_languageKey); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Localization Value", GUILayout.MaxWidth(190)); _textLanguage.text = EditorGUILayout.TextArea(_textLanguage.text); EditorGUILayout.EndHorizontal(); if (GUILayout.Button("InsertToExcel")) { //配置Excel路徑 string languagePath = @"C:\Users\Administrator\Desktop\StarForce-master\Excels\Localization.xlsx"; if (string.IsNullOrEmpty(_languageKey.stringValue)) { EditorUtility.DisplayDialog("插入信息失敗", "key值不可爲空,信息插入失敗", "ok"); return; } if (_isFileUse(languagePath)) { EditorUtility.DisplayDialog("插入信息失敗", string.Format("{0}文件被佔用,信息插入失敗", languagePath), "ok"); return; } //key列索引 string keyCol = "1"; string keyInfo = _languageKey.stringValue; //value列索引 string valueCol = "2"; string valueInfo = _textLanguage.text; Process process = new Process(); process.StartInfo.FileName = Application.dataPath + "/../Tools/InsertStringToExcel/WriteMsgToExcel.exe"; process.StartInfo.Arguments = string.Format("{0} {1} {2} {3} {4}", languagePath, keyCol, keyInfo, valueCol, valueInfo); process.StartInfo.WorkingDirectory = Path.GetDirectoryName(process.StartInfo.FileName); process.Start(); } _object.ApplyModifiedProperties(); } private bool _isFileUse(string filePath) { bool isUse = true; StreamWriter sw = null; try { sw = new StreamWriter(filePath, true); isUse = false; } catch { } finally { if (sw != null) { sw.Close(); } } return isUse; } }
對應的demo在這裏(修改excel路徑,Editor下操做便可)翻譯