How do you create a serializable list of classes implementing an interface?
4 replies, posted
Say you have something like this:
public interface Foo
{
void DoThing();
}
public class Bar : Foo
{
public string MyField;
public void DoThing()
{
Debug.Log(MyField);
}
}
public class BetterBar : Foo
{
public int MyBetterField;
public void DoThing()
{
Debug.Log(MyBetterField);
}
}
In another file:
public class FooHolder : MonoBehaviour
{
public List<Foo> TheFoos;
}
So Unity doesn't serialize interfaces of course.
What I found is that you can for example have a class that wraps Foo like
public class FooClass
{
public Foo MyFoo;
}
Then you can use a CustomPropertyDrawer and a dropdown to select the type and ... well this is where I get stuck.
I would like it to do some magic in OnGUI I guess. Has anyone tried implementing something similar?
What you can do is write a custom inspector for your object, this'll allow you to add custom controls in the inspector window that you can modify your object with.
You're basically duplicating the same class but then for the inspector, so it depends on how automatic you want the process to be, but with some C# reflection I think that should be possible as well.
Unity
Do you have something more concrete? Most of the editor examples are when you have a MonoBehavior that has built-in types as properties instead of custom classes, and especially not interfaces.
Not at the moment, but I'll see if I can cook something up. Been a while dealing with some more in-depth stuff C#.
Alright so.
So you have your base class, let's call it 'Step', and it derives from MonoBehaviour.
Then, you have some fields and/or virtual methods.
In your derived classes, StepSpecialA and StepSpecialB, you figure out how to implement your virtual methods.
Although you have to add these MonoBehaviours to gameObjects, you get custom data as well as functionality which can all be plucked from the inspector.
I almost thought I could do it with scriptable objects but those cannot reference scene objects, so this is the best method I've come across so far. It sounds gross, but I haven't found a less gross method, so.
Sorry, you need to Log In to post a reply to this thread.