打开Localization.cs
首先将静态类变成非静态类,继承MonoBehaviour类;
增加静态变量(单例模式)
static Localization mInstance;
static public Localization instance
{
get
{
if (mInstance == null)
{
mInstance = Object.FindObjectOfType(typeof(Localization)) as Localization;
if (mInstance == null)
{
GameObject go = new GameObject("_Localization");
DontDestroyOnLoad(go);
mInstance = go.AddComponent<Localization>();
}
}
return mInstance;
}
}
public string startingLanguage = "china";
public TextAsset[] languages;
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
string myLanguage;
public string currentLanguage
{
get
{
return myLanguage;
}
set
{
if (myLanguage != value)
{
startingLanguage = value;
if (!string.IsNullOrEmpty(value))
{
// Check the referenced assets first
if (languages != null)
{
for (int i = 0, imax = languages.Length; i < imax; ++i)
{
TextAsset asset = languages[i];
if (asset != null && asset.name == value)
{
Load(asset);
return;
}
}
}
// Not a referenced asset -- try to load it dynamically
TextAsset txt = Resources.Load(value, typeof(TextAsset)) as TextAsset;
if (txt != null)
{
Load(txt);
return;
}
}
// Either the language is null, or it wasn't found
myDictionary.Clear();
PlayerPrefs.DeleteKey("Language");
}
}
}
然后在Awake()方法中开始调用:
void Awake()
{
if (mInstance == null)
{
mInstance = this;
DontDestroyOnLoad(gameObject);
currentLanguage = PlayerPrefs.GetString("Language", startingLanguage);
if (string.IsNullOrEmpty(mLanguage) && (languages != null && languages.Length > 0))
{
currentLanguage = languages[0].name;
}
}
else Destroy(gameObject);
}
之后在场景中新建一个物体,并把这个脚本添加在这个物体上;
最后在工程新建文件夹“Localization”,把我们的语言(.txt)放进这个文件夹下;然后把语言文件拖进上面新建物体的脚本中,如图:
语言文件,例如:
再我们的Lable组件下添加:
并且把key设置为“UI_Play2”;
这样就OK了。