基于 Luban + QFramework 的本地化
Luban:主要用于将 Excel 数据转换为可供游戏使用的数据(如 Json 格式),因此可将各国语言存储在 Excel 中便于管理,可用其他同类方案代替
QFramework:本案例主要使用它的事件机制(观察者模式),实现语言的即时切换,可用其他同类方案代替
一、建立多语言 Excel 表
##var | id | simplified_chinese | english |
---|---|---|---|
##type | int | string | string |
10000 | 穿甲弹 | Pierce Bullet | |
10001 | 医疗包 | Medical Kit | |
10002 | 兴奋剂 | Dope | |
10003 | 荆棘 | Thorn | |
10005 | 近视眼 | Myopia | |
10006 | 印钞机 | Money Printing Machine | |
10007 | 撬棍 | Crowbar | |
10008 | 弹匣 | Gun Magazine |
然后通过 Luban 生成代码:
-
该表作为数据表
local.TbTextLocalization.cs
-
该表的条目的对象为:
LocalizedText.cs
(大致内容如下)public sealed partial class LocalizedText : Luban.BeanBase { public readonly int Id; public readonly string SimplifiedChinese; public readonly string English; }
二、创建本地化控制器/文本本地化模块组件
using cfg;
namespace XXX
{
public enum Language
{
SimplifiedChinese,
English,
}
public static class LocalizationController
{
private static Language _curLanguage = Language.SimplifiedChinese;
public static Language CurLanguage
{
get => _curLanguage;
set
{
if (_curLanguage == value) return;
_curLanguage = value;
// QFramework 中提供的事件发送,用于通知所有文本本地化模块“当前语言已改变”
XXXGame.Interface.SendEvent<CurrentLanguageChangedEvent>();
}
}
public static string GetLocalizedText(int id)
{
// TbTextLocalization 为 Luban 生成的表数据
LocalizedText lt = TableController.Tables.TbTextLocalization[id];
return CurLanguage switch
{
Language.SimplifiedChinese => lt.SimplifiedChinese,
Language.English => lt.English,
_ => lt.English,
};
}
}
}
文本本地化模块组件用于附加在普通的 Text 或 Text Mesh Pro 组件上,为其附加本地化功能
using QFramework;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace XXX
{
public class TextLocalizationModule : MonoBehaviour, ICanRegisterEvent
{
[SerializeField]
private int _id;
public int Id
{
get { return _id; }
set
{
_id = value;
UpdateText();
}
}
private Text _textComponent;
private TextMeshPro _tmp;
private void Awake()
{
_textComponent = GetComponent<Text>();
_tmp = GetComponent<TextMeshPro>();
// QFramework 中提供的事件注册:每当语言更改便触发 CurrentLanguageChangedEvent
this.RegisterEvent<CurrentLanguageChangedEvent>(_ =>
{
UpdateText();
}).UnRegisterWhenGameObjectDestroyed(gameObject);
}
private void UpdateText()
{
if (_textComponent != null)
{
_textComponent.text = LocalizationController.GetLocalizedText(Id);
}
else if (_tmp != null)
{
_tmp.text = LocalizationController.GetLocalizedText(Id);
}
}
public IArchitecture GetArchitecture()
{
return XXXGame.Interface;
}
}
}
三、使用
对于固定的 UI 元素,在其文本 UI 组件中附上刚才的“文本本地化模块组件”脚本组件,并在编辑器中指定对应的 Id 值即可;对于预制体中文本 UI 则用代码的方式指定对应的 Id 值即可。
当当前语言设置切换时可以即时切换画面中文本语言(由于游戏中敏感信息,效果图在脱敏制作后上传)