自用记录贴,针对小体量工程写的一个最简单的多语言管理脚本。
csharp
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
/// <summary>
/// 多语言管理类
/// 语言表使用csv存储,每行为一个单词,每行用逗号分割多国语言
/// csv内容: 第一行 测试1,test1
/// 第二行 测试2,test2
/// </summary>
public class LanguageManager
{
public static LanguageType languageType;
/// <summary>
/// 解析语言文件结束后的回调,使用协程读取,会导致读取比awake慢
/// </summary>
public static event UnityAction analysisDoneCall;
/// <summary>
/// 储存多语言内容的字典类
/// </summary>
private static Dictionary<int, List<string>> languageDic = new Dictionary<int, List<string>>();
/// <summary>
/// 在工程初始化处调用此方法
/// 使用协程读取语言文件,webgl和安卓端只能使用协程读取文件
/// </summary>
/// <param name="monoIE"></param>
public static void ReadLanguageFileByIE(MonoBehaviour monoIE)
{
monoIE.StartCoroutine(IEReadFile(GetLanguageFilePath(), OnReadConfigCall));
}
/// <summary>
/// 在需要使用文字的位置调用此方法
/// 显示层调用,获取对应csv中的编号,从1开始的内容
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static string GetLanguageContent(int index)
{
index--;
if (languageDic.ContainsKey(index))
{
int typeIndex = (int)languageType;
if (typeIndex >= languageDic[index].Count)
{
Debug.LogErrorFormat("索引={0},没有{1}类型对应的内容", index, languageType.ToString());
return "";
}
return languageDic[index][typeIndex];
}
else
{
Debug.LogError("没有对应索引的多语言内容 index=" + index);
return "";
}
}
private static void AddLanguageDic(int key, string[] text)
{
if (languageDic.ContainsKey(key))
{
languageDic[key].AddRange(text);
}
else
{
List<string> list = new List<string>(text);
languageDic.Add(key, list);
}
}
/// <summary>
/// 保存语言文件的路径
/// </summary>
/// <returns></returns>
public static string GetLanguageFilePath()
{
return Application.streamingAssetsPath + "/Language.csv";
}
/// <summary>
/// 解析文件内容
/// </summary>
/// <param name="readText"></param>
public static void OnReadConfigCall(string readText)
{
languageDic.Clear();
string[] content = readText.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < content.Length; i++)
{
AddLanguageDic(i, content[i].Split(','));
}
analysisDoneCall?.Invoke();
analysisDoneCall = null;
}
public static IEnumerator IEReadFile(string path, UnityAction<string> call)
{
using (UnityWebRequest uwr = UnityWebRequest.Get(path))
{
yield return uwr.SendWebRequest();
if (uwr.isDone && uwr.error == null)
{
if (call != null)
{
call(uwr.downloadHandler.text);
}
Debug.LogFormat("读取文件路径={0},content={1}", path, uwr.downloadHandler.text);
}
}
}
}
public enum LanguageType
{
Chinese=0,
English=1,
}