当前位置:   article > 正文

Unity多语言_unity多语言方案

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;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311

初始化语言,绑定语言文本
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,
        }
        );
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

切换语言
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");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

绑定到需要多语言的按钮文本上
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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

Assets/Scripts/Chinese.txt

Text Main_01 = [语言]
Text Main_02 = [返回]
Text Main_03 = []
Text Main_04 = []
  • 1
  • 2
  • 3
  • 4

Assets/Scripts/English.txt

Text Main_01 = [Language]
Text Main_02 = [Return]
Text Main_03 = [Yes]
Text Main_04 = [No]
  • 1
  • 2
  • 3
  • 4

读写Json的脚本

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

{
    "LanguageString": "English"
}
  • 1
  • 2
  • 3

实现对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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/106827
推荐阅读
相关标签
  

闽ICP备14008679号