using System; using Module.Inspector.Editor.Utilities; using UnityEditor; using UnityEngine; namespace Module.Inspector.Editor { [CustomPropertyDrawer(typeof(IntToEnum))] internal sealed class DrawerIntToEnum : DrawerPropertyDrawer { private GUIContent[] names; private int[] values; public override bool Draw(Rect position, DrawerPropertyAttribute attribute, SerializedProperty property, GUIContent label, EditorPropertyUtility.Result result) { if (property.propertyType != SerializedPropertyType.Integer) return false; var att = (IntToEnum)attribute; FetchLayerNames(att); EditorGUI.BeginChangeCheck(); EditorGUI.BeginProperty(position, label, property); { int index = Array.IndexOf(values, property.intValue); int newIndex = EditorGUI.Popup(position, label, index, names); if (newIndex != -1 && index != newIndex) property.intValue = values[newIndex]; } EditorGUI.EndProperty(); bool changed = EditorGUI.EndChangeCheck(); if (changed) property.serializedObject.ApplyModifiedProperties(); return true; } public override string GetErrorMessage(SerializedProperty property) { return "Only supports integers"; } private void FetchLayerNames(IntToEnum attribute) { if (names != null) return; Type type = attribute.GetValidType(); string[] arrNames = Enum.GetNames(type); Array arrValues = Enum.GetValues(type); names = new GUIContent[arrNames.Length]; values = new int[arrValues.Length]; for (var i = 0; i < names.Length; i++) { names[i] = new GUIContent(arrNames[i]); values[i] = Convert.ToInt32(arrValues.GetValue(i)); } } } }