- Home /
Show a dropdown for C# classes in inspector.
I have an object which should have a plugged in behaviors. Currently each behavior is a plain C# class which uses polymorphism.
My question is: can I make an inspector dropdown button which given a set of behaviors would allow me to choose one? So I would like something like this:
[SerializeField]
List<Behavior> behaviors;
Where Behavior is an abstract class. The inspector should show a dropdown for each list element allowing me to choose a class which inherits from the abstract class. This list of inheriting classes can be obtained through reflection so all I really need is a dropdown to represent a Behavior in the inspector using a list of strings.
If this cannot be done are there any other ways of making it work. I know I can use scriptable objects and create a file for each behavior and plug those is but that introduces a lot of unnecessary files which I would like to avoid.
Answer by SolidAlloy · May 17, 2020 at 12:10 PM
It can be done in a few lines using ClassTypeReference:
[ClassExtends(typeof(Behaviour))]
[SerializeField] private ClassTypeReference someBehaviourType;
Answer by Xamtox · Dec 05, 2019 at 01:57 PM
You could create a enum:
private enum MyClasses { MyClassA, MyClassB, MyClassC }
[SerializeField] private MyClasses class;
And then create an ugly switch:
public MyBaseClass ReturnMyClass {
switch (class) {
case MyClasses.MyClassA: return new MyClassA();
case MyClasses.MyClassB: return new MyClassB();
...
}
}
For each new behaviour you'll only need to add new enum value and new switch case. With [Flags] attribute you could select multiple behaviours if you wish (obviously you'll need to rewrite switch for that case).
This is probably the simplest way to achieve required task, but hardly the best. I'm sure, there is much cleaner solution using editor scripts.
Yeah, that is why I wanted to use Reflection. The concept is simple of what I want, just a drop down with string values which internally creates an instance (easy using reflection). I just do not know how to express it in script.