"Injecting" an interface into an object

I have a class for my enemy which extends from MonoBehaviour. This class has inside a reference to another class that I have made:

[RequireComponent (typeof (Action))]
public class EnemyController : MonoBehaviour {
    public Action action;      // Action is an interface!

Now, I would like to “inject” this dependency using the Unity GUI, just dragging and dropping the desired object into the EnemyController. The problem is that Action is an interface, so Unity tells me that the class can’t be abstract.

My idea was to be able to use different types of Actions… Is it possible to do this?


Bad news: Unity’s built-in serialization isn’t polymorphic. Your Action reference can point at any given subclass during runtime, of course, but when Unity writes the data to disk, it will serialize only an Action and its associated fields.

You can find some discussion about this, online, but this thread is a pretty good overview.

Some people work around this by integrating other serialization libraries, such as JsonFX, MiniJSON, Protobufs, or so on. Others use Unity to serialize primitive data containers, which they use to reconstruct necessary objects at runtime.