Skip to content

Instantly share code, notes, and snippets.

@partlyhuman
Created October 27, 2017 19:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save partlyhuman/4c6f3e7141ef468a80432bb960ee8b21 to your computer and use it in GitHub Desktop.
Save partlyhuman/4c6f3e7141ef468a80432bb960ee8b21 to your computer and use it in GitHub Desktop.
Helpful labels for serialized arrays accessed by enum types
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
}
@partlyhuman
Copy link
Author

partlyhuman commented Oct 27, 2017

Accepting suggestions for better ways to find the underlying array index...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment