【Unity编辑器拓展】实现ScriptableObject的结构体结构中,枚举变量显示中文描述
问题描述【旧问题】在Unity开发中ScriptableObjectSO常使用枚举来定义选项。为了保持代码规范枚举值通常使用英文但在Unity编辑器的Inspector面板中纯英文显示对非英语母语的策划或美术人员不够友好难以快速理解每个选项的含义。此问题已在我这一篇文章中解决【Unity编辑器拓展】实现ScriptableObject中枚举显示中文描述_unity 怎么给枚举加上注释 可以在inspector上看到-CSDN博客【新问题】虽然上一篇文章初步解决了旧问题但代码中还存在一个遗漏目前还没有处理 ScriptableObjectSO文件里的嵌套结构。具体来说就是 SO 中包含的结构体里包裹着枚举变量我们需要将其[Description]特性中的描述信息替换为该枚举变量本身。如下图所示解决方案在原有的代码基础上添加上对结构体这样的嵌套结构的处理1定义带中文描述的枚举using System.ComponentModel; // 引用命名空间 - 为枚举添加描述属性 // 物品图标分类 public enum ItemIconKey { [Description(Weapon - 武器图标)] Weapon, [Description(Armor - 防具图标)] Armor, [Description(Accessory - 饰品图标)] Accessory, [Description(Healing - 治疗类物品图标)] Healing, [Description(Revive - 复活类物品图标)] Revive, [Description(Cure - 接触异常状态类物品图标)] Cure, [Description(KeyItem - 任务物品/关键物品图标)] KeyItem, }2编写编辑器脚本编写一个Unity编辑器脚本通过反射读取[ Description ] 特性并替换显示文本文件名LocalizedEnumDrawer.cs存放路径Assets/Editor/LocalizedEnumDrawer.csusing UnityEngine; using UnityEditor; using System; using System.ComponentModel; using System.Reflection; /// summary /// 自定义属性绘制器用于枚举类型的本地化显示 /// 继承自PropertyDrawer并应用于所有Enum类型 /// /summary [CustomPropertyDrawer(typeof(Enum), true)] public class LocalizedEnumDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType ! SerializedPropertyType.Enum) { EditorGUI.PropertyField(position, property, label, true); return; } Type enumType fieldInfo.FieldType; if (enumType null || !enumType.IsEnum) { EditorGUI.PropertyField(position, property, label, true); return; } string[] enumNames property.enumNames; string[] displayNames new string[enumNames.Length]; for (int i 0; i enumNames.Length; i) { FieldInfo enumField enumType.GetField(enumNames[i]); DescriptionAttribute[] attributes (DescriptionAttribute[])enumField.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length 0) { displayNames[i] attributes[0].Description; } else { displayNames[i] enumNames[i]; } } EditorGUI.BeginChangeCheck(); int newIndex EditorGUI.Popup(position, label.text, property.enumValueIndex, displayNames); if (EditorGUI.EndChangeCheck()) { property.enumValueIndex newIndex; } } }完成效果