Unity3D实现多语言切换

项目现在需要做多语言切换部分,下面是一个基本多语言切换实现

1.

首先建立一个类来存放字符,其中包括一个静态方法来根据Key和语言类型获取对应字符

using System.Collections;
using System.Collections.Generic;
using UnityEngine; public static class multiLangConst { static Dictionary<string, string> LangMap_en = new Dictionary<string, string>{
{"txt_name", "Name"},
}; static Dictionary<string, string> LangMap_cn = new Dictionary<string, string>{
{"txt_name", "名字"},
}; public static string GetValue(string languageType, string key) {
if (languageType == "en") {
return LangMap_en[key];
} else if (languageType == "cn") {
return LangMap_cn[key];
}
return "N/A";
}
}

2.

然后建立一个全局的委托

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System; public class GameManager : MonoBehaviour { public delegate void OnLanguageChanged(string type);
public static OnLanguageChanged onLanguageChanged = null;
public void SetupLanguage(string type) {
if (onLanguageChanged != null) {
onLanguageChanged(type);
}
}
}

3.

最后是一个Handler,挂在有Text组件的对象上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; public class multiLangHandler : MonoBehaviour { [SerializeField, Header("Langkey")]
private string LangKey = ""; void Awake() {
GameManager.onLanguageChanged += onLanguageChanged;
} private void OnDestroy() {
GameManager.onLanguageChanged -= onLanguageChanged;
} void onLanguageChanged(string languageType) {
Text text = this.gameObject.GetComponent<Text>();
if (text != null) {
var value = multiLangConst.GetValue(languageType, LangKey);
text.text = value;
return;
}
}
}

最后通过按钮来调用GameManager下面的SetupLanguage方法来进行语言切换。

上一篇:OpenStack云平台网络模式及其工作机制


下一篇:Django -> debug模式下的静态文件服务(/media/)