Unity多语言

Unity多语言

实现效果:

点击语言按钮前:
在这里插入图片描述
点击语言按钮后:
在这里插入图片描述

LanguageLod.cs绑定到空对象即可,选择中文和英文文本
在这里插入图片描述

语言切换按钮
LanguageChange.cs绑定到切换语言的按钮上,事件中添加LanguageChange中的click方法
在这里插入图片描述

多语言显示文本
在所有需要多语言的文本上绑定TextValue.cs
填写语言文本Chinese.txt 和English.txt 中对应的Key值
Key值只允许使用英文大小写字符、数字和下划线“_”
以当前为例:当前Text需要显示的内容是“语言”和“Language”所以填写“Main_01”
在这里插入图片描述

所有脚本目录
在这里插入图片描述

全部脚本

多语言核心脚本
Assets/Scripts/LanguageManager.cs

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

public class LanguageManager : MonoBehaviour
{
    
    
    private static LanguageManager _Manager;
    /// <summary>
    /// 单例模式可方便调用
    /// </summary>
    public static LanguageManager GetManager
    {
    
    
        get
        {
    
    
            if (_Manager == null)
            {
    
    
                GameObject Go = new GameObject("LanguageManager");
                GameObject.DontDestroyOnLoad(Go);
                _Manager = Go.AddComponent<LanguageManager>();
            }
            return _Manager;
        }
    }
    //切换语言回调
    private List<Action> CallBack = new List<Action>();
    /// <summary>
    /// 语言类型
    /// </summary>
    public enum LanguageType
    {
    
    
        /// <summary>
        /// 中文
        /// </summary>
        Chinese,
        /// <summary>
        /// 英文
        /// </summary>
        English,
        /// <summary>
        /// 其他语言
        /// </summary>
        Other
    }
    //默认语言类型
    private LanguageType m_Language = LanguageType.Chinese;
    
	/// <summary>
    /// 加载时从Json文本中获取保存的语言类型
    /// </summary>
    private void Awake()
    {
    
    
        TestJson testJson = new TestJson();
        string language = testJson.ReadLanguage();
        if (language == "Chinese")
        {
    
    
            m_Language = LanguageType.Chinese;
        }
        else if (language == "English")
        {
    
    
            m_Language = LanguageType.English;
        }
    }

    /// <summary>
    /// 初始化语言包
    /// </summary>
    /// <param name="language"></param>
    public void Init(params Language[] language)
    {
    
    
        ReadText(language);
    }
    /// <summary>
    /// 获取值
    /// </summary>
    /// <param name="Key"></param>
    /// <returns></returns>
    public string GetValueToKey(string Key)
    {
    
    
        if (!Dic_Language.ContainsKey(m_Language))
            return Key;
        Dictionary<string, string> Temp_Language = new Dictionary<string, string>();
        if (!Dic_Language.TryGetValue(m_Language, out Temp_Language))
            return Key;
        return GetValue(Key, Temp_Language);
    }
    /// <summary>
    /// 添加语言切换回调(方便实现项目中的语言切换功能)
    /// </summary>
    /// <param name="action"></param>
    public void Add(Action action)
    {
    
    
        if (CallBack.Contains(action))
            return;
        CallBack.Add(action);
    }
    /// <summary>
    /// 获取当前语言
    /// </summary>
    public LanguageType Get_LanguageType
    {
    
    
        get
        {
    
    
            return m_Language;
        }
    }
    /// <summary>
    /// 切换语言
    /// </summary>
    public LanguageType Setting_LanguageType
    {
    
    
        set
        {
    
    
            m_Language = value;
            for (int i = 0; i < CallBack.Count; i++)
            {
    
    
                var fn = CallBack[i];
                if (fn != null)
                    fn();
            }
        }
    }
    /// <summary>
    /// 语言字典
    /// </summary>
    protected Dictionary<LanguageType, Dictionary<string, string>> Dic_Language = new Dictionary<LanguageType, Dictionary<string, string>>();



    private void ReadText(Language[] varLanguage)
    {
    
    
        for (int i = 0; i < varLanguage.Length; i++)
        {
    
    
            Language Temp_Language = varLanguage[i];
            if (Dic_Language.ContainsKey(Temp_Language.m_Type))
            {
    
    
                Dictionary<string, string> Temp_DIC_Language = Dic_Language[Temp_Language.m_Type];
                ReadTextAsset(Temp_Language, Temp_DIC_Language);
            }
            else
            {
    
    
                Dictionary<string, string> Temp_DIC_Language = new Dictionary<string, string>();
                ReadTextAsset(Temp_Language, Temp_DIC_Language);
                Dic_Language.Add(Temp_Language.m_Type, Temp_DIC_Language);
            }
        }
    }
    /// <summary>
    /// 读取Txt文本
    /// </summary>
    /// <param name="varTextAsset"></param>
    /// <param name="varDic"></param>
    private void ReadTextAsset(Language varTextAsset, Dictionary<string, string> varDic)
    {
    
    
        string Text;
        if (varTextAsset.m_Txt != null)
            Text = varTextAsset.m_Txt.text;
        else if (varTextAsset.bytes != null)
            Text = System.Text.Encoding.UTF8.GetString(varTextAsset.bytes);
        else
            Text = varTextAsset.text;
        if (string.IsNullOrEmpty(Text))
            return;

        string temp_Content = Text.Replace("\r\n", "\f");

        string[] varContent = temp_Content.Split('\f');
        if (varContent == null)
            return;
        List<string> LanguageList = RemovedNullString(varContent);
        if (LanguageList.Count == 0)
            return;
        for (int i = 0; i < LanguageList.Count; i++)
        {
    
    
            string Temp_Content = LanguageList[i];

            if (!Temp_Content.Contains("Text"))
                continue;
            string Key;
            string Value = "";
            string[] TempLanguage = Temp_Content.Split('=');
            if (TempLanguage.Length < 2)
                continue;
            Key = TempLanguage[0];
            if (!TestingKeyLegal(ref Key))
                continue;
            for (int jx = 1; jx < TempLanguage.Length; jx++)
            {
    
    
                if (jx == 1)
                    Value += TempLanguage[jx];
                else
                    Value += "=" + TempLanguage[jx];
            }
            Value = TestingValueLegal(Value);
            if (!varDic.ContainsKey(Key))
                varDic.Add(Key, Value);
        }
    }
    /// <summary>
    /// 移除数组中无效的字符串
    /// </summary>
    /// <param name="varContent"></param>
    /// <returns></returns>
    private List<string> RemovedNullString(string[] varContent)
    {
    
    
        List<string> LanguageList = new List<string>();
        for (int i = 0; i < varContent.Length; i++)
        {
    
    
            if (string.IsNullOrEmpty(varContent[i]))
                continue;
            LanguageList.Add(varContent[i]);
        }
        return LanguageList;
    }
    /// <summary>
    /// 检测Key的合法性
    /// </summary>
    /// <param name="Key"></param>
    /// <returns></returns>
    private bool TestingKeyLegal(ref string Key)
    {
    
    
        //string TempKey = Key;
        Key = Key.Trim();
        string[] content = Key.Split(' ');
        if (content.Length != 2)
            return false;
        if (content[0] != "Text")
            return false;
        Key = content[1];
        //限制Key值得组成成员
        string TestingString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_";
        char[] tempkey = Key.ToCharArray();
        for (int i = 0; i < tempkey.Length; i++)
        {
    
    
            char ms = tempkey[i];
            if (!TestingString.Contains(ms.ToString()))
                return false;
        }
        return true;
    }
    /// <summary>
    /// 检测Value值的合法性
    /// </summary>
    /// <param name="Value"></param>
    /// <returns></returns>
    private string TestingValueLegal(string Value)
    {
    
    
        //先移除两头无效的空格
        Value = Value.Trim();
        //当值中存在中括号时,移除两头的中括号
        if (Value.Contains("[") && Value.Contains("]"))
        {
    
    
            Value = Value.Trim('[', ']');
        }
        return Value;
    }


    private string GetValue(string Key, Dictionary<string, string> varDic)
    {
    
    
        if (!varDic.ContainsKey(Key))
            return Key;
        string Value = "";
        if (varDic.TryGetValue(Key, out Value))
            return ClearSpilth(Value);
        return Key;
    }
    /// <summary>
    /// 移除多余的字符
    /// </summary>
    /// <param name="varValue"></param>
    /// <returns></returns>
    private string ClearSpilth(string varValue)
    {
    
    
        string Value = varValue;
        if (Value.Contains("\\n"))
            Value = Value.Replace("\\n", "\n");
        if (Value.Contains("\\r"))
            Value = Value.Replace("\\r", "\r");
        if (Value.Contains("\\\\"))
            Value = Value.Replace("\\\\", "\\");
        if (Value.Contains("\\t"))
            Value = Value.Replace("\\t", "\t");
        if (Value.Contains("\\v"))
            Value = Value.Replace("\\v", "\v");
        return Value;
    }

    /// <summary>
    /// 语言结构
    /// </summary>
    public struct Language
    {
    
    
        /// <summary>
        /// 语言类型
        /// </summary>
        public LanguageType m_Type;
        /// <summary>
        /// 语言文本
        /// </summary>
        public TextAsset m_Txt;
        /// <summary>
        /// 语言文本
        /// </summary>
        public byte[] bytes;
        /// <summary>
        /// 语言文本
        /// </summary>
        public string text;
    }
}

初始化语言,绑定语言文本
Assets/Scripts/LanguageLod.cs

using UnityEngine;
using static LanguageManager;

public class LanguageLod : MonoBehaviour
{
    
    
    public TextAsset chinese;
    public TextAsset english;
    private void Awake()
    {
    
    
        //初始化语言包
        LanguageManager.GetManager.Init(new Language
        {
    
    
            m_Type = LanguageType.Chinese,
            m_Txt = chinese,
        },
        new Language
        {
    
    
            m_Type = LanguageType.English,
            m_Txt = english,
        }
        );
    }
}

切换语言
Assets/Scripts/LanguageChange.cs

using UnityEngine;

public class LanguageChange : MonoBehaviour
{
    
    
    public void click()
    {
    
    
        TestJson testJson = gameObject.AddComponent<TestJson>();
        LanguageManager languageManager = LanguageManager.GetManager;

        if (languageManager.Get_LanguageType == LanguageManager.LanguageType.Chinese)
        {
    
    
            languageManager.Setting_LanguageType = LanguageManager.LanguageType.English;
            testJson.WriteLanguage("English");
        }
        else if (languageManager.Get_LanguageType == LanguageManager.LanguageType.English)
        {
    
    
            languageManager.Setting_LanguageType = LanguageManager.LanguageType.Chinese;
            testJson.WriteLanguage("Chinese");
        }
    }
}

绑定到需要多语言的按钮文本上
Assets/Scripts/ValueToKey.cs

using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("UI/TextValue")]
public class ValueToKey : MonoBehaviour
{
    
    
    [SerializeField]
    private string Key;

    public string GetKey {
    
     get {
    
     return Key; } }
    /// <summary>
    /// 
    /// </summary>
    public Text m_Content;
    public TextMesh m_Content_3D;

    private void Awake()
    {
    
    
        LanguageManager.GetManager.Add(GetValueToKey);
        m_Content_3D = this.transform.GetComponent<TextMesh>();
        if (m_Content == null)
            m_Content = this.transform.GetComponent<Text>();
        GetValueToKey();
    }
    /// <summary>
    /// 设置Key值并更新Value
    /// </summary>
    /// <param name="varKey"></param>
    public void SettingKey(string varKey)
    {
    
    
        Key = varKey;
        GetValueToKey();
    }
    private void OnEnable()
    {
    
    
        if (!string.IsNullOrEmpty(Key))
        {
    
    
            GetValueToKey();
        }
    }
    private void GetValueToKey()
    {
    
    
        string Value = LanguageManager.GetManager.GetValueToKey(Key);
        if (m_Content != null)
            m_Content.text = Value;
        if (m_Content_3D != null)
            m_Content_3D.text = Value;
    }
}

Assets/Scripts/Chinese.txt

Text Main_01 = [语言]
Text Main_02 = [返回]
Text Main_03 = []
Text Main_04 = []

Assets/Scripts/English.txt

Text Main_01 = [Language]
Text Main_02 = [Return]
Text Main_03 = [Yes]
Text Main_04 = [No]

读写Json的脚本

为了保存程序关闭时的语言类型,加入了Json文本
在这里插入图片描述
Assets/StreamingAssets/Language.json

{
    
    
    "LanguageString": "English"
}

实现对Json文本读写方法脚本
TestJson.cs

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

public class TestJson : MonoBehaviour
{
    
    
    string jsonpath;

    public void WriteLanguage(string langua)
    {
    
    
        jsonpath = Application.streamingAssetsPath + "/Language.json";
        Languagedata languagedata = new Languagedata();
        languagedata.LanguageString = langua;
        string json = JsonUtility.ToJson(languagedata, true);
        File.WriteAllText(jsonpath, json);
    }
    public string ReadLanguage()
    {
    
    
        jsonpath = Application.streamingAssetsPath + "/Language.json";
        string json = File.ReadAllText(jsonpath);
        Languagedata languagedata = new Languagedata();
        languagedata = JsonUtility.FromJson<Languagedata>(json);
        return languagedata.LanguageString;
    }
}
[Serializable]
public class FaMenKeyAndValue
{
    
    
    public string key;
    public bool value;
}
public class Jsondata
{
    
    
    public List<FaMenKeyAndValue> faMenKeyAndValue;
}
public class Languagedata
{
    
    
    public string LanguageString;
}

猜你喜欢

转载自blog.csdn.net/w291720094/article/details/128930758