使用CustomPropertyDrawer实现编辑器扩展只显示部分枚举值和枚举值中文显示
Unity默认的枚举值不支持数字开头,也不支持汉字;而且只能显示全部的枚举项,无法只显示部分选项
新建脚本EnumTest,代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnumTest : MonoBehaviour { public EAttackLevel level; } public enum EAttackLevel { None, Low, Med, High, }
①我想不显示None选项
②我想枚举选项以数字开头
③我想枚举选项显示汉语
使用CustomPropertyDrawer以上需求都可以:
新建脚本EnumAttackLevelAttribute:
1 using System.Collections.Generic; 2 using UnityEditor; 3 using UnityEngine; 4 5 public class EnumAttackLevelAttribute : HeaderAttribute 6 { 7 public EnumAttackLevelAttribute(string header) : base(header) 8 { 9 } 10 } 11 12 [CustomPropertyDrawer(typeof(EnumAttackLevelAttribute))] 13 public class EnumAttackLevelDrawer : PropertyDrawer 14 { 15 private readonly List<string> m_displayNames = new List<string>(); 16 17 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) 18 { 19 var att = (EnumAttackLevelAttribute)attribute; 20 var type = property.serializedObject.targetObject.GetType(); 21 var field = type.GetField(property.name); 22 var enumtype = field.FieldType; 23 foreach (var enumName in property.enumNames) 24 { 25 var enumfield = enumtype.GetField(enumName); 26 if (enumfield.Name == "None")//不显示None 27 { 28 continue; 29 } 30 var hds = enumfield.GetCustomAttributes(typeof(HeaderAttribute), false); 31 m_displayNames.Add(hds.Length <= 0 ? enumName : ((HeaderAttribute)hds[0]).header);//如果加了自定义属性,显示自定义名,否则显示枚举选项名 32 } 33 EditorGUI.BeginChangeCheck(); 34 var value = EditorGUI.Popup(position, att.header, property.enumValueIndex, m_displayNames.ToArray()); 35 if (EditorGUI.EndChangeCheck()) 36 { 37 property.enumValueIndex = value + 1;//因为我们隐藏了一个显示项None,这儿别忘了加1 38 Debug.LogError("value " + property.enumValueIndex.ToString()); 39 } 40 } 41 }
EnumTest脚本改成如下:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class EnumTest : MonoBehaviour 6 { 7 [EnumAttackLevel("攻击级别")] 8 public EAttackLevel level; 9 } 10 11 public enum EAttackLevel 12 { 13 [Header("0空")] 14 None, 15 16 [Header("1低")] 17 Low, 18 19 [Header("2中")] 20 Med, 21 22 [Header("3高")] 23 High, 24 }
再在Unity中看我们的枚举值:
实现所有需求