Created
October 27, 2017 19:34
-
-
Save partlyhuman/4c6f3e7141ef468a80432bb960ee8b21 to your computer and use it in GitHub Desktop.
Helpful labels for serialized arrays accessed by enum types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.RegularExpressions; | |
using UnityEngine; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
namespace com.hololabs | |
{ | |
/// <summary> | |
/// When you're serializing arrays or lists to be accessed by the underlying value of an enum, | |
/// using the [EnumIndexedArray] annotation will allow the inspector to label array indices correctly | |
/// as the enum value rather than as "Element 0". | |
/// </summary> | |
/// <example> | |
/// enum Direction { Left, Right, Up, Down } | |
/// | |
/// [SerializedField] | |
/// [EnumIndexedArray(typeof(Direction))] | |
/// public float[] SpeedForDirection; | |
/// </example> | |
public class EnumIndexedArray : PropertyAttribute | |
{ | |
public readonly Type indexType; | |
public EnumIndexedArray(Type indexType) | |
{ | |
this.indexType = indexType; | |
} | |
} | |
#if UNITY_EDITOR | |
[CustomPropertyDrawer(typeof(EnumIndexedArray))] | |
public class EnumIndexedArrayInspector : PropertyDrawer | |
{ | |
static readonly Regex EXTRACT_INDEX = new Regex(@"\.data\[(\d+)\]$"); | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
Match match = EXTRACT_INDEX.Match(property.propertyPath); | |
if (match.Success) | |
{ | |
Type enumType = ((EnumIndexedArray) this.attribute).indexType; | |
int arrayIndex = int.Parse(match.Groups[1].Value); | |
string enumName = Enum.GetName(enumType, arrayIndex); | |
if (enumName != null) | |
{ | |
label = new GUIContent(enumName); | |
} | |
} | |
EditorGUI.PropertyField(position, property, label); | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Accepting suggestions for better ways to find the underlying array index...