EnumAttirbuteAttribute.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using System;
  3. #if UNITY_EDITOR
  4. using UnityEditor;
  5. using System.Reflection;
  6. using System.Text.RegularExpressions;
  7. #endif
  8. /// <summary>
  9. /// 设置枚举名称
  10. /// </summary>
  11. #if UNITY_EDITOR
  12. [AttributeUsage(AttributeTargets.Field)]
  13. #endif
  14. public class EnumAttirbute : PropertyAttribute
  15. {
  16. /// <summary>
  17. /// 枚举名称
  18. /// </summary>
  19. public string name;
  20. public EnumAttirbute(string name)
  21. {
  22. this.name = name;
  23. }
  24. }
  25. #if UNITY_EDITOR
  26. [CustomPropertyDrawer(typeof(EnumAttirbute))]
  27. public class EnumNameDrawer : PropertyDrawer
  28. {
  29. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  30. {
  31. // 替换属性名称
  32. EnumAttirbute enumAttirbute = (EnumAttirbute)attribute;
  33. label.text = enumAttirbute.name;
  34. bool isElement = Regex.IsMatch(property.displayName, "Element \\d+");
  35. if (isElement)
  36. {
  37. label.text = property.displayName;
  38. }
  39. if (property.propertyType == SerializedPropertyType.Enum)
  40. {
  41. DrawEnum(position, property, label);
  42. }
  43. else
  44. {
  45. EditorGUI.PropertyField(position, property, label, true);
  46. }
  47. }
  48. /// <summary>
  49. /// 重新绘制枚举类型属性
  50. /// </summary>
  51. /// <param name="position"></param>
  52. /// <param name="property"></param>
  53. /// <param name="label"></param>
  54. private void DrawEnum(Rect position, SerializedProperty property, GUIContent label)
  55. {
  56. EditorGUI.BeginChangeCheck();
  57. Type type = fieldInfo.FieldType;
  58. string[] names = property.enumNames;
  59. string[] values = new string[names.Length];
  60. while (type.IsArray)
  61. {
  62. type = type.GetElementType();
  63. }
  64. for (int i = 0; i < names.Length; ++i)
  65. {
  66. FieldInfo info = type.GetField(names[i]);
  67. EnumAttirbute[] enumAttributes = (EnumAttirbute[])info.GetCustomAttributes(typeof(EnumAttirbute), false);
  68. values[i] = enumAttributes.Length == 0 ? names[i] : enumAttributes[0].name;
  69. }
  70. int index = EditorGUI.Popup(position, label.text, property.enumValueIndex, values);
  71. if (EditorGUI.EndChangeCheck() && index != -1)
  72. {
  73. property.enumValueIndex = index;
  74. }
  75. }
  76. }
  77. #endif