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包,那么需要

相关推荐
游乐码7 小时前
Unity基础(十二)资源异步加载
unity·游戏引擎
weixin_424294679 小时前
程序不知道写在了什么位置???
unity
weixin_441940019 小时前
vuforia ar unity实验教程
unity·游戏引擎·ar
WarPigs13 小时前
Unity AB包资源加载管理器
unity
程序员正茂14 小时前
EasyAR使用OpenCV下USB摄像头作为自定义相机
opencv·unity·easyar
诙_14 小时前
unity——C#
unity·c#·游戏引擎
winlife_15 小时前
全程用 AI 做一款商业级手游 · EP9 收尾与复盘:做到了哪,没做到哪,边界在哪
java·开发语言·人工智能·unity·ai编程·游戏开发·mcp
EQ-雪梨蛋花汤17 小时前
【Unity笔记】Unity URP 透明玻璃出现白色光斑?Directional Light 镜面高光问题分析与解决
3d·unity·数字孪生
游乐码18 小时前
Unity基础(十三)资源卸载
unity·游戏引擎
winlife_18 小时前
全程用 AI 做一款商业级手游 · EP7 表现层与手感:从“能跑“到“摸起来爽“
java·开发语言·人工智能·unity·ai编程·游戏开发·mcp