- Home /
disable or remove enum entry from inspector
public enum MyEnum {
MyEntry0,
MyEntry1,
MyEntry2,
MyEntry3,
MyEntry4
}
public MyEnum myEnum;
lets say i want to make sure that MyEntry0 and MyEntry3 are unselectable. whats the best way of doing that, without creating a seperate enum?
Comment
Best Answer
Answer by Hellium · Jan 16 at 10:21 PM
If you want to prevent the option from being selected from every script, you can go with the InspectorNameAttribute
attribute.
public enum MyEnum
{
MyEntry0,
MyEntry1,
// The name should be the "nice looking" name of the previous entry
// So we can't use `nameof(MyEnum.MyEntry1)`
[InspectorNameAttribute("My Entry 1")]
MyEntry2,
MyEntry3,
MyEntry4
}
If you want something a per-script solution, you'll need a custom attribute and property drawer
using System.Collections.Generic;
using UnityEngine;
public class MyEnumFilterAttribute : PropertyAttribute
{
public int[] Values { get; private set; }
public string[] Labels { get; private set; }
public MyEnumFilterAttribute(params MyEnum[] ignoredValues)
{
List<int> values = new List<int>((int[]) System.Enum.GetValues(typeof(MyEnum)));
List<string> labels = new List<string>(System.Enum.GetNames(typeof(MyEnum)));
for (int i = ignoredValues.Length - 1 ; i >= 0 ; i--)
{
int index = values.IndexOf((int) ignoredValues[i]);
values.RemoveAt(index);
labels.RemoveAt(index);
}
Values = values.ToArray();
Labels = labels.ToArray();
}
}
In an Editor
folder
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(MyEnumFilterAttribute))]
public class EnumFilterAttributeEditor : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MyEnumFilterAttribute filterAttribute = ((MyEnumFilterAttribute) attribute);
property.intValue = EditorGUI.IntPopup(position, label, property.intValue, System.Array.ConvertAll(filterAttribute.Labels, l => new GUIContent(l)), filterAttribute.Values);
}
}
[MyEnumFilter(MyEnum.MyEntry0, MyEnum.MyEntry2)]
public MyEnum myEnum;
i cant seem to get the 1st one to work, but the 2nd one works like a charm. thanks for the help!