Unity简单多语言支持方案

小游戏读取文件太麻烦,修改优化的本地化类,已亲测使用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LocalizationManager
{

    //单例模式
    private static LocalizationManager _instance;
    public static LocalizationManager GetInstance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new LocalizationManager();
            } 
            return _instance;
        }
    }


    //选择自已需要的本地语言    
    public string language = "English";
    private Dictionary<string, string> dic = new Dictionary<string, string>();

    public void Chinese() {
        dic.Clear();

        Debug.Log("Chinese");

        dic.Add("One", "一颗骰子");
        dic.Add("Three", "三颗骰子");
        dic.Add("Five", "五颗骰子");
        dic.Add("MoreGames", "更多游戏");
        dic.Add("Points", "点数");

    }

    public void English()
    {
        dic.Clear();

        Debug.Log("English");

        dic.Add("One", "One");
        dic.Add("Three", "Three");
        dic.Add("Five", "Five");
        dic.Add("MoreGames", "More games");
        dic.Add("Points", "Points");

    }

    private SystemLanguage GetLanguage()
    {
        return Application.systemLanguage;
    }

    public void Clear() {
        dic.Clear();
    }

    /// 获取value    
    /// </summary>    
    /// <param name="key"></param>    
    /// <returns></returns>    
    public string GetValue(string key)
    {
        if (dic.Count <= 0) {
            if (GetLanguage() == SystemLanguage.Chinese
                || GetLanguage() == SystemLanguage.ChineseSimplified
                || GetLanguage() == SystemLanguage.ChineseTraditional)
            {
                Chinese();
            }
            else {
                English();
                //Chinese();
            }
        }

        if (dic.ContainsKey(key) == false)
        {
            return key;
        }
        string value = null;
        dic.TryGetValue(key, out value);
        return value;
    }

}

Unity Text控件挂载下面脚本,并输入参数key

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LocalizationText : MonoBehaviour
{

    public string key = "";

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Text>().text = LocalizationManager.GetInstance.GetValue(key);
    }
}

原创博客,转载请标明出处:https://www.geekapp.cn/archives/640.html
上一篇
下一篇