代碼一,語言管理類:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LanguageManager : MonoBehaviour {
private static LanguageManager _instance = null;
private Dictionary<string, string> dic = new Dictionary<string, string>();
public static LanguageManager GetInstance()
{
return _instance;
}
void Awake()
{
if (_instance == null)
{
_instance = this;
//如果切換場景時,希望單例中的數據不清空
//DontDestroyOnLoad(gameObject);//加載場景時不消毀
}
else
{
//保留老的單例,刪除新的單例對象
Destroy(this.gameObject);
}
//得到語言
//GetLanguage(GameController.Instance().gameData.language);
GetLanguage(PlayerPrefs.GetString("language"));
Debug.Log("得到語言 :" + PlayerPrefs.GetString("language"));
}
/// <summary>
/// 獲取語言
/// </summary>
/// <param name="language"></param>
public void GetLanguage(string language)
{
TextAsset ta = Resources.Load("Language/" + language) as TextAsset;
string text = ta.text;
string[] lines = text.Split('\n');
foreach (string line in lines)
{
if (line == null)
{
continue;
}
//如果單行有“=”才做操作
if (line.Contains("="))
{
string[] keyAndValue = line.Split('=');
//當字典中存在該key時,先移除在添加
if (dic.ContainsKey(keyAndValue[0]))
{
dic.Remove(keyAndValue[0]);
dic.Add(keyAndValue[0], keyAndValue[1]);
}
else
{
dic.Add(keyAndValue[0], keyAndValue[1]);
}
}
}
}
/// <summary>
/// 獲取value
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key)
{
if (dic.ContainsKey(key) == false)
{
return null;
}
string value = null;
dic.TryGetValue(key, out value);
return value;
}
}
需要設置的單個對象(將腳本掛載在該text對象上,設置Key,根據文本中的key找到value)
代碼爲:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LocalizationText : MonoBehaviour {
public string key = "";
string language = "";
private Text nameText;
void Start () {
nameText = GetComponent<Text>();
language = GameController.Instance().gameData.language;
//語言是英語,根據語言設置字體大小
if (GameController.Instance().gameData.language == "en")
{
nameText.fontSize = 50;
}
nameText.text = LanguageManager.GetInstance().GetValue(key);
}
void Update()
{
if (language != GameController.Instance().gameData.language)
{
language = GameController.Instance().gameData.language;
nameText.text = LanguageManager.GetInstance().GetValue(key);
}
}
}
文本中的顯示: