unity多语言框架

  1. Text在生命周期函数里去查自己该显示的文本。所以还是自己实现一个text;
  2. 需要一个校验程序,能找到整个项目所有text,并且对每种语言json都有它的键。

文本控件绑定key

整个项目每个Text控件都有一个id。可以把Text所在的game Object名字当id,或者继承Text实现一个有id的。

cs 复制代码
using UnityEngine;
using UnityEngine.UI;
namespace MyFarm
{
    public class LocalText:Text
    {
        [SerializeField]
        public string key;
    }
}

然后发现继承Text,加一个key,检查器也显示不出来,必须自定义检查器编辑器:

cs 复制代码
using UnityEditor;
namespace MyFarm
{
    [CustomEditor(typeof(LocalText), true)]
    public class LocalTextEditor: UnityEditor.UI.TextEditor
    {
        LocalText m_Text;
        protected override void OnEnable()
        {
            base.OnEnable();
            m_Text = (LocalText)target;
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            m_Text.key = EditorGUILayout.TextField("key", m_Text.key);
        }
    }
}

或许这也不是最好的方案,应该弄一个类,require Text控件。就不用重写检查器了。

考虑到继承Text需要把项目资源的Text控件一个个替换,重新设置对齐、字大小、字颜色,还是组合比较好!

cs 复制代码
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
namespace MyFarm
{
    [RequireComponent(typeof(Text))]
    public class LocalTextKey:MonoBehaviour
    {
        [SerializeField]
        string key;
        public string Key => key;
        Text _text;
        Text text
        {
            get
            {
                if(_text == null)
                {
                    _text = GetComponent<Text>();
                }
                return _text;
            }
        }
        private void Start()
        {
            UpdateText(MySettingsManager.Instance.settings.gameLanguage);
            MySettingsManager.Instance.onLanguageChanged += UpdateText;
        }
        private void OnDestroy()
        {
            MySettingsManager.Instance.onLanguageChanged -= UpdateText;
        }
        public void UpdateText(string langName)
        {
            var dic = LanguageManager.Instance.LangDic;
            if (dic.ContainsKey(langName))
            {
                var langSO = dic[langName];
                FieldInfo field = langSO.GetType().GetField(key);
                if (field != null)
                {
                    text.text = field.GetValue(langSO).ToString();
                }
            }
        }

    }
}

一种语言的配置文件:json还是SO

每种语言一个json,里面是id-文本的字典。可以用SO编辑,生成json。或者直接用SO也行;

语言配置文件放哪?

如果想支持热更新,放AB包,那么需要

相关推荐
还是大剑师兰特20 小时前
Unity3D(Unity)完整详细介绍
unity·游戏引擎
ellis19701 天前
u3d插件xLua[七]例6 Coroutine
unity
还是大剑师兰特1 天前
Unity 从零搭建简易3D场景(新手分步教程)
3d·unity·游戏引擎
神码编程1 天前
【Unity】TankBattle联机坦克大战(三)创建关卡(生成地块)
unity·游戏引擎·帧同步·坦克大战
淡海水1 天前
C#与常用数据结构源码剖析-全篇导览
开发语言·数据结构·unity·面试·职场和发展·c#
玖玥拾2 天前
Unity3D RPG 入门项目(四)背包拖拽、物品悬浮提示、项目开发思维
3d·unity·游戏引擎
xcLeigh2 天前
Unity基础:Start与Update方法——Unity脚本生命周期初探
java·unity·游戏引擎·教程
郝学胜-神的一滴2 天前
[简化版 GAMES 104] 现代游戏引擎 05:游戏引擎世界构建核心机制深度解析
c++·程序人生·unity·游戏引擎·计算机图形学·opengl
LONGZETECH3 天前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降
大数据·算法·unity·架构·无人机
五仁烧饼4 天前
Unity Addressables 静默资源策略
游戏·unity·addressables