Skip to content

Instantly share code, notes, and snippets.

@shane-harper
Created December 13, 2018 11:49
Show Gist options
  • Save shane-harper/f9ccc04dfe8f851edf4cc2e63a01fdec to your computer and use it in GitHub Desktop.
Save shane-harper/f9ccc04dfe8f851edf4cc2e63a01fdec to your computer and use it in GitHub Desktop.
Use enum values as labels on arrays use [LabelledEnumArray(typeof( ??? ))]
using System;
using UnityEngine;
/// <summary>
/// Use enum values as labels on an array
/// </summary>
/// <remarks>Should not be placed in an Editor folder</remarks>
public class LabelledEnumArrayAttribute : PropertyAttribute
{
public readonly Type EnumType;
public LabelledEnumArrayAttribute(Type enumType)
{
EnumType = enumType;
}
}
using System;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Property drawer for LabelledEnumArrayAttribute
/// </summary>
/// <remarks>Must be placed in an Editor folder</remarks>
[CustomPropertyDrawer(typeof(LabelledEnumArrayAttribute))]
public class LabelledEnumArrayDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Get property index and enum type
var index = GetPropertyIndex(property.propertyPath);
var type = ((LabelledEnumArrayAttribute) attribute).EnumType;
// Get name, update label if one is found
var name = Enum.GetName(type, index);
if (!string.IsNullOrEmpty(name))
label = new GUIContent(name);
// Draw property
EditorGUI.PropertyField(position, property, label);
}
/// <summary>
/// Reads the index from the property path string
/// </summary>
private static int GetPropertyIndex(string path)
{
var start = path.LastIndexOf('[') + 1;
var end = path.LastIndexOf(']');
return int.Parse(path.Substring(start, end - start));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment