summaryrefslogtreecommitdiff
path: root/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/PackageTools/Editor/EnumFlagDrawer.cs
blob: 8e14970f8191a7a99b5c07b5e554e7cd1439444c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Pathfinding {
	[CustomPropertyDrawer(typeof(EnumFlagAttribute))]
	public class EnumFlagDrawer : PropertyDrawer {
		public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
			Enum targetEnum = GetBaseProperty<Enum>(property);

			EditorGUI.BeginProperty(position, label, property);
			EditorGUI.BeginChangeCheck();
#if UNITY_2017_3_OR_NEWER
			Enum enumNew = EditorGUI.EnumFlagsField(position, label, targetEnum);
#else
			Enum enumNew = EditorGUI.EnumMaskField(position, label, targetEnum);
#endif
			if (EditorGUI.EndChangeCheck() || !property.hasMultipleDifferentValues) {
				property.intValue = (int)Convert.ChangeType(enumNew, targetEnum.GetType());
			}
			EditorGUI.EndProperty();
		}

		static T GetBaseProperty<T>(SerializedProperty prop) {
			// Separate the steps it takes to get to this property
			string[] separatedPaths = prop.propertyPath.Split('.');

			// Go down to the root of this serialized property
			System.Object reflectionTarget = prop.serializedObject.targetObject as object;
			// Walk down the path to get the target object
			foreach (var path in separatedPaths) {
				FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				reflectionTarget = fieldInfo.GetValue(reflectionTarget);
			}
			return (T)reflectionTarget;
		}
	}
}