EnumLabelAttribute.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using UnityEngine;
  3. #if UNITY_EDITOR
  4. using UnityEditor;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. #endif
  9. [AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
  10. public class EnumLabelAttribute : PropertyAttribute
  11. {
  12. public string label;
  13. public EnumLabelAttribute(string label)
  14. {
  15. this.label = label;
  16. }
  17. }
  18. #if UNITY_EDITOR
  19. [CustomPropertyDrawer(typeof(EnumLabelAttribute))]
  20. public class EnumLabelDrawer : PropertyDrawer
  21. {
  22. private Dictionary<string, string> customEnumNames = new Dictionary<string, string>();
  23. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  24. {
  25. SetUpCustomEnumNames(property, property.enumNames);
  26. if (property.propertyType == SerializedPropertyType.Enum)
  27. {
  28. EditorGUI.BeginChangeCheck();
  29. string[] displayedOptions = property.enumNames
  30. .Where(enumName => customEnumNames.ContainsKey(enumName))
  31. .Select<string, string>(enumName => customEnumNames[enumName])
  32. .ToArray();
  33. int selectedIndex = EditorGUI.Popup(position, enumLabelAttribute.label, property.enumValueIndex, displayedOptions);
  34. if (EditorGUI.EndChangeCheck())
  35. {
  36. property.enumValueIndex = selectedIndex;
  37. }
  38. }
  39. }
  40. private EnumLabelAttribute enumLabelAttribute
  41. {
  42. get
  43. {
  44. return (EnumLabelAttribute)attribute;
  45. }
  46. }
  47. public void SetUpCustomEnumNames(SerializedProperty property, string[] enumNames)
  48. {
  49. Type type = property.serializedObject.targetObject.GetType();
  50. foreach (FieldInfo fieldInfo in type.GetFields())
  51. {
  52. object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(EnumLabelAttribute), false);
  53. foreach (EnumLabelAttribute customAttribute in customAttributes)
  54. {
  55. Type enumType = fieldInfo.FieldType;
  56. foreach (string enumName in enumNames)
  57. {
  58. FieldInfo field = enumType.GetField(enumName);
  59. if (field == null) continue;
  60. EnumLabelAttribute[] attrs = (EnumLabelAttribute[])field.GetCustomAttributes(customAttribute.GetType(), false);
  61. if (!customEnumNames.ContainsKey(enumName))
  62. {
  63. foreach (EnumLabelAttribute labelAttribute in attrs)
  64. {
  65. customEnumNames.Add(enumName, labelAttribute.label);
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. #endif