Custom Property Drawer for Interface derived MonoBehaviours

I am currently stumped with the following problem: I want to write a custom property drawer for a property. The property should ideally be of an interface type of my choice. The property drawer should work similar to the object field, as you should be able to drag and drop assets or scene objects into it. But the objects should be restricted to Unity objects, that are derived from the property’s interface type.

So if I have an ISwitchable interface, and a TrapDoor and a LightController MonoBehaviour implementing this interface, I want to be able to drag TrapDoor, LightController or any other future MonoBehaviour that I will derive from ISwitchable.

I have already tried some things. If I use a regular ObjectField for example, and make the object type the interface, it will not allow any objects derived from that interface to be dragged into the field. If I make the ObjectField of type MonoBehaviour, I can drag any component into the field and have to write weird workarounds to filter out all the objects that don’t implement my interface of choice. Also very annoying that I can’t use ObjectField.BindProperty on a field with the SerializeReference attribute, so I also can’t really make the field of the interface type and make it of the MonoBehaviour type as well, using other checks and workarounds to make sure that the correct types are assigned.

Am I overlooking something obvious? Or is it really so hard to do what I am trying to do?

Google around a bit, this has been fairly well covered in many different threads.

Here’s one quick example that can give you some more relevant reading:

Unity doesn’t support serializing Unity objects via interfaces to begin with, so you have to solve the serialization problem before you even start with the inspector side of things. Remember, an editor/property drawer does not change what Unity can and can’t serialize.

Most solutions you’ll see out there involves some kind of wrapper reference object, which can be cumbersome. Odin Inspector + Serializer can do it without the need for such objects, but is unstable for use with prefabs.

Basically yes. Until Unity supports this kind of serialization natively, there is no 100% elegant solution.

1 Like