Unity中实现字段/枚举编辑器中显示中文(中文枚举、中文标签)
在unity开发编辑器相关经常会碰到定义的字段显示在Inspector是中文,枚举也经常碰到显示的是字段定义时候的英文,程序还好,但是如果编辑器交给策划编辑,策划的英文水平不可保证,会很头大,所以还是有个中文标签/中文枚举会很方便。
效果如下:
话不多说,直接贴实现,Editor部分可自行拆分放到Editor文件下下,当前用宏做区分,HeaderComponent继承自PropertyAttribute,再利用即可
1. 中文标签,新建ChineseLabelAttribute.cs
/**************************************************** Author: Flamesky Mail: flamesky@live.com Date: 2022/2/24 10:48:36 Function: Nothing *****************************************************/ using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class ChineseLabelAttribute : HeaderAttribute { public ChineseLabelAttribute(string header) : base(header) { } } #if UNITY_EDITOR [CustomPropertyDrawer(typeof(ChineseLabelAttribute))] public class ChineseLabelDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var att = attribute as ChineseLabelAttribute; EditorGUI.PropertyField(position, property, new GUIContent(att.header), true); } } #endif
2. 中文枚举,新建EnumLabelAttribute.cs
/**************************************************** Author: Flamesky Mail: flamesky@live.com Date: 2022/2/22 20:30:40 Function: Nothing *****************************************************/ using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif public class EnumLabelAttribute : HeaderAttribute { public EnumLabelAttribute(string header) : base(header) { } } #if UNITY_EDITOR [CustomPropertyDrawer(typeof(EnumLabelAttribute))] public class EnumLabelDrawer : PropertyDrawer { private readonly List<string> m_displayNames = new List<string>(); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var att = (EnumLabelAttribute)attribute; var type = property.serializedObject.targetObject.GetType(); var field = type.GetField(property.name); var enumtype = field.FieldType; foreach (var enumName in property.enumNames) { var enumfield = enumtype.GetField(enumName); var hds = enumfield.GetCustomAttributes(typeof(HeaderAttribute), false); m_displayNames.Add(hds.Length <= 0 ? enumName : ((HeaderAttribute)hds[0]).header); } EditorGUI.BeginChangeCheck(); var value = EditorGUI.Popup(position, att.header, property.enumValueIndex, m_displayNames.ToArray()); if (EditorGUI.EndChangeCheck()) { property.enumValueIndex = value; } } } #endif
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步