1. 在Assets 新增一 Folder 並命名為 Resources,並準備不同語言之txt檔案放入其中
2. 檔案內容範例如下
3. 新增腳本 LanguageMgr.cs
public class LanguageMgr : MonoBehaviour
{
private static LanguageMgr
instance = null;
public static LanguageMgr
Instance
{
get { return instance; }
}
[SerializeField]
private SystemLanguage
language;
private Dictionary<string, string> dict = new Dictionary<string, string>();
private void loadLanguage()
{
// 根據手機系統語言變換語言
if (Application.systemLanguage ==
SystemLanguage.ChineseTraditional)
{
language = SystemLanguage.ChineseTraditional;
}
else if
(Application.systemLanguage == SystemLanguage.ChineseSimplified)
{
language
= SystemLanguage.ChineseSimplified;
}
else if
(Application.systemLanguage == SystemLanguage.English)
{
language = SystemLanguage.English;
}
else
{
language = SystemLanguage.English;
}
//加载文件
TextAsset
ta = Resources.Load<TextAsset>(language.ToString());
if (ta == null)
{
Debug.LogWarning("沒有這個語言的翻譯文件");
return;
}
//獲取每一行
string[] lines = ta.text.Split('\n');
//獲取 key value
for (int i = 0; i <
lines.Length; i++)
{
//檢測
if (string.IsNullOrEmpty(lines[i]))
continue;
//獲取 key:kv[0] value
kv[1]
string[] kv =
lines[i].Split(':');
//保存到字典
dict.Add(kv[0], kv[1]);
Debug.Log(string.Format("key:{0},
value:{1}", kv[0], kv[1]));
}
}
void Awake()
{
instance = this;
loadLanguage();
}
public string GetText(string key)
{
if
(dict.ContainsKey(key))
return dict[key];
else//沒有這個 key
{
return string.Empty;
}
}
}
4. 將LanguageMgr.cs 腳本掛到 Canvas 上,可看見各語言名稱
5. 新增腳本 UIText.cs
using System.Collections;
using
System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIText : MonoBehaviour
{
/// <summary>
/// 對應的key
/// </summary>
[SerializeField]
private string key;
void Start()
{
//設置key之后 才需要改变
if (!string.IsNullOrEmpty(key))
{
//獲取對應的value
string value =
LanguageMgr.Instance.GetText(this.key);
if (!string.IsNullOrEmpty(value))
//给text组件赋值
GetComponent<Text>().text = value;
}
}
}
6. 將 UIText.cs 掛到欲國際化的 Text 組件上,並輸入 key 值,即可實現國際化。