- Home /
How can i show enum description in Inspector?
I wrote a script which has a public enum variable. When i attach this script to a gameobject, as a component, the Unity Editor would change enum variable into a dropdown list in Inspector automatically. My enum type is like this:
enum MyEnum {
[Description("Description of option 1")] Option1,
[Description("Description of option 2")] Option2
}
The problem is the dropdown list in Inspertor just show me "Option1" and "Option2",the description fields are ignored. How can i make Inspertor to show my description as a choice name in a dropdown list instead of show enum item directly, so that i can make my script more user-friendly for the other guys.
Thanks
Answer by Bunny83 · Aug 12, 2012 at 12:39 AM
The only way is to create a custom inspector for your class and use reflection to read the attributes. I actually never saw attributes on enum members, so i'm not sure if that's even possible. It's much easier to seperate the helptext from the enum:
enum MyEnum
{
Option1,
Option2
}
You can simply use a EditorGUI.Popup / EditorGUILayout.Popup to display the dropdown.
public MyEnum myValue;
In your custom inspector:
private static string[] m_MyEnumDescriptions = new string[]
{
"Description of option 1",
"Description of option 2"
};
// In OnInspectorGUI
myValue = (MyEnum)EditorGUILayout.Popup((int)myValue, m_MyEnumDescriptions);
This of course assumes that you use a linear enum starting at 0 like the one you showed in your example.
Thank you, that is just what i want to know, to override a default Inspector behavior. It is possible to add description in enum type, it's under System.Component$$anonymous$$odel, and can pass through $$anonymous$$ono compiler. Seems Unity Inspector just didn't implement it yet.
Attributes are optional data information that can be added to classes, fields, methods. I'm not sure if it's even possible to add them to enum members as well. Anyway attributes don't really force a certain behaviour. $$anonymous$$ostly they are used by the compiler or serializer to get additional meta data about a class / member.
You can also create a new custom attribute and attach it to a field, but it always depends on the interpreting system if and how this data is used.
Again, attributes are just additional data without any behaviour.
If it's possible to add attributes to enum-members you can read them normally via reflection in your custom inspector. $$anonymous$$aybe i find some time for some tests on that topic ;)
Answer by Bluk · Aug 12, 2012 at 12:38 AM
enum MyEnum {
Option1,
Option2
}
public var test:MyEnum;
Uhmm should that be an answer? I don't get how that should answer his question since that's what's already in the question...
Also your code is written in UnityScript (Unity's javascript) while the code in question is clearly C# ;)