EnumFlagDrawer.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Reflection;
  3. using UnityEditor;
  4. using UnityEngine;
  5. namespace Pathfinding {
  6. [CustomPropertyDrawer(typeof(EnumFlagAttribute))]
  7. public class EnumFlagDrawer : PropertyDrawer {
  8. public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
  9. Enum targetEnum = GetBaseProperty<Enum>(property);
  10. EditorGUI.BeginProperty(position, label, property);
  11. EditorGUI.BeginChangeCheck();
  12. #if UNITY_2017_3_OR_NEWER
  13. Enum enumNew = EditorGUI.EnumFlagsField(position, label, targetEnum);
  14. #else
  15. Enum enumNew = EditorGUI.EnumMaskField(position, label, targetEnum);
  16. #endif
  17. if (EditorGUI.EndChangeCheck() || !property.hasMultipleDifferentValues) {
  18. property.intValue = (int)Convert.ChangeType(enumNew, targetEnum.GetType());
  19. }
  20. EditorGUI.EndProperty();
  21. }
  22. static T GetBaseProperty<T>(SerializedProperty prop) {
  23. // Separate the steps it takes to get to this property
  24. string[] separatedPaths = prop.propertyPath.Split('.');
  25. // Go down to the root of this serialized property
  26. System.Object reflectionTarget = prop.serializedObject.targetObject as object;
  27. // Walk down the path to get the target object
  28. foreach (var path in separatedPaths) {
  29. FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  30. reflectionTarget = fieldInfo.GetValue(reflectionTarget);
  31. }
  32. return (T)reflectionTarget;
  33. }
  34. }
  35. }