Unity 多语言文本

多语言文本解决方案

      • 关键代码
        • 解决方案一 Application.systemLanguage
            • unity官方API 能判定40多种语言
        • 解决方案二 Android
            • 根据个人需求选用API,比如我需要判断菲律宾语 en-PH。菲律宾语言环境下,getLanguage返回 en 为英语,不满足需求,getCountry为 PH 可以完成判断
          • Unity代码
          • Android国家代码点这里
      • Code
          • Excel转Json
          • 功能代码
          • 调用Json

关键代码

解决方案一 Application.systemLanguage

unity官方API 能判定40多种语言
switch(Application.systemLanguage){
     
    case SystemLanguage.Chinese://中文
    case SystemLanguage.ChineseSimplified://中文简体
	//这两个要一起判断,有的机型返回Chinese,有的返回ChineseSimplified
    break;
    case SystemLanguage.ChineseTraditional://中文繁体
    break;
    case SystemLanguage.English://
    break;
    case SystemLanguage.Unknown://
    break;
    //...  
}

解决方案二 Android

因我的项目马来语,菲律宾语,方案一不能判定,采用AndroidAPI

getResources().getConfiguration().locale.getLanguage()
//如下图,getLanguage返回值为前半截 "en"  指英语
getResources().getConfiguration().locale.getCountry()
//如下图,getCountry返回值为后半截  "US"	 指国家

Unity 多语言文本_第1张图片

根据个人需求选用API,比如我需要判断菲律宾语 en-PH。菲律宾语言环境下,getLanguage返回 en 为英语,不满足需求,getCountry为 PH 可以完成判断
Unity代码
if (Application.platform == RuntimePlatform.Android)
{
     
    //获得系统国家代码
    AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject _unityContext = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaObject locale = _unityContext.Call<AndroidJavaObject>("getResources").Call<AndroidJavaObject>("getConfiguration").Get<AndroidJavaObject>("locale");
    string countryCode = locale.Call<string>("getCountry");

    return countryCode;
}
else
{
     
    return "CN";
}
Android国家代码点这里

提示:夜神模拟器可以设置不同语言环境测试,很方便。

Code

Excel转Json

翻译或策划可能提供的文档是下图这样,第一行可能还有汉语写的什么语言,我去掉了,也可以在代码的遍历忽略第一行
在这里插入图片描述
拿到的json可能是这样
Unity 多语言文本_第2张图片
或这样(有的会被Unicode)
Unity 多语言文本_第3张图片

我是单独弄了个工程做这个,路径什么的比较随便

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using OfficeOpenXml;
using LitJson;

public class ExcelToXML
{
     
    static Dictionary<string, string>[] dics;

    [MenuItem("Tools/读取Excel")]
    public static void ReadExcel()
    {
     
        dics = new Dictionary<string, string>[9];
        for (int i = 0; i < 9; i++)
        {
     
            if (dics[i] == null)
            {
     
                dics[i] = new Dictionary<string, string>();
            }
        }
        string tempKey = "";
        string outPutDir = Application.dataPath + "\\" + "Excel.xlsx";//路径根据自己需求来
        using (ExcelPackage package = new ExcelPackage(new FileStream(outPutDir, FileMode.Open)))
        {
     
            for (int i = 1; i <= package.Workbook.Worksheets.Count; ++i)
            {
     
                ExcelWorksheet sheet = package.Workbook.Worksheets[i];
                for (int m = sheet.Dimension.Start.Row, n = sheet.Dimension.End.Row; m <= n; m++)
                {
     
                    for (int j = sheet.Dimension.Start.Column, k = sheet.Dimension.End.Column; j <= k; j++)
                    {
     
                        if (sheet.GetValue(m, j) != null)
                        {
     
                            string str = sheet.GetValue(m, j).ToString();

                            if (str != null)
                            {
     
                                // do something
                                Debug.Log(str + "----" + m + "/" + j);
                                if (j == 1)
                                {
     
                                    tempKey = str;
                                }
                                else
                                {
     
                                    dics[j - 2].Add(tempKey, str);
                                }
                            }
                        }

                    }

                }

            }
        }
        Write();
    }
    // 简体中文	英文	西班牙	YinNi	MaLai	YueNan	FeiLvBin	TaiGuo	BaXi
    public static void Write()
    {
     
        string[] list =  {
      "Chinese", "English", "Xibanya", "Yinni", "Malaixiya", "Yuenan", "Feilvbin", "Taiguo", "Baxi" };
        for (int i = 0; i < dics.Length; i++)
        {
     
            //找到当前路径
            FileInfo file = new FileInfo(Application.dataPath + "\\" + list[i] + ".Json"); //路径根据自己需求来
            //判断有没有文件,有则打开文件,,没有创建后打开文件
            StreamWriter sw = file.CreateText();
            //ToJson接口将你的列表类传进去,,并自动转换为string类型
            string json = JsonMapper.ToJson(dics[i]);
            Debug.Log(json);
            //将转换好的字符串存进文件,
            // sw.Write()
            sw.WriteLine(json);
            // File.WriteAllText(Application.dataPath+"\\"+i+".Json",json ,System.Text.Encoding.UTF8);
            //注意释放资源
            sw.Close();
            sw.Dispose();

            AssetDatabase.Refresh();
        }

    }
}

功能代码
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
public enum LanguageEnum//根据需求自己添加
{
     
    NONE,
    CHINESE,
    ENGLISH,
    FEILVBIN,
    MALAIXIYA
}
public class Languages : Singleton<Languages>//单例脚本就不写了
{
     
    private LanguageEnum _curLanguage = LanguageEnum.NONE;
    public LanguageEnum CurLanguage
    {
     
        get
        {
     
            if (_curLanguage == LanguageEnum.NONE)
            {
     
                _curLanguage = GetLanguage();
            }
            return _curLanguage;
        }

    }
    private Dictionary<string, string> _dicTexts = new Dictionary<string, string>();
    public void Init()
    {
     
        string name = "Chinese";
        switch (CurLanguage)
        {
     
            case LanguageEnum.CHINESE:
                name = "Chinese";
                break;
            case LanguageEnum.ENGLISH:
                name = "English";
                break;
            case LanguageEnum.FEILVBIN:
                name = "Feilvbin";
                break;
            case LanguageEnum.MALAIXIYA:
                name = "Malaixiya";
                break;
        }
        string fileName = name;
        string url = "config/" + fileName;
        var self = this;
        Resources.Load(url);
        string str = (Resources.Load(url) as TextAsset).text;
        _dicTexts = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);//我用的JosnDotnet 根据自己方法解析
        switch (Application.systemLanguage)
        {
     
            case SystemLanguage.Chinese://中文
            case SystemLanguage.ChineseSimplified://中文简体
            case SystemLanguage.ChineseTraditional://中文繁体

                break;
            case SystemLanguage.English:
                break;
            case SystemLanguage.Unknown:
                break;
            default:
                break;
        }

    }
	
    public string GetText(string key)
    {
     
        if (_dicTexts.ContainsKey(key))
        {
     
            string str = _dicTexts[key].Replace("\\n", "\n");
            return Unicode2String(str);
        }
        else
        {
     
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
     
                Debug.LogError($"未获取到:{key}的文案");
                return "无文案";
            }
            else
            {
     
                return "";
            }

        }
    }
    /// 
    /// Unicode转字符串
    /// 
    /// 经过Unicode编码的字符串
    /// 正常字符串
    public static string Unicode2String(string source)
    {
     
        return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                    source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
    }
    public LanguageEnum GetCountry()
    {
     
        if (Application.platform == RuntimePlatform.Android)
        {
     
            //获得系统国家代码
            AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject _unityContext = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
            AndroidJavaObject locale = _unityContext.Call<AndroidJavaObject>("getResources").Call<AndroidJavaObject>("getConfiguration").Get<AndroidJavaObject>("locale");
            string country = locale.Call<string>("getCountry");

            return GetLanguage(country);
        }
        else
        {
     
            return LanguageEnum.CHINESE;
        }
    }
    private LanguageEnum GetLanguage(string code)
    {
     
        LanguageEnum temp = LanguageEnum.CHINESE;
        switch (code)
        {
     
            case "PH":
                temp = LanguageEnum.FEILVBIN;//菲律宾Filipino PH   PHL
                break;
            case "MY":
                temp = LanguageEnum.MALAIXIYA;//马来西亚MY MYS
                break;
            case "CN":
            case "TW":
                temp = LanguageEnum.CHINESE;
                break;
            default:
                temp = LanguageEnum.ENGLISH;
                break;
        }
        return temp;
    }
}

调用Json
Languages.Instance.Init();//游戏开始调用初始化


text.text = Languages.Instance.GetText("001006");//界面使用

你可能感兴趣的:(Unity,Unity_Android,unity,android,安卓)