'enforcing' a Type in the Unity Editor

Let's start with a picture

Download the code here

what's going on here?

There are two property fields that accept any MonoBehaviour. Both properties are decorated with an attribute that accepts a type (in this case an interface) as a parameter. If you populate the properties with an object that does not implement said type, the field will turn red.

why not make the property an interface?

This is a Unity limitiation. Unity does not serialize interfaces. Only serializable properties will show up in the inspector. Thus, no dice.

why choose this solution?

It's quick, dirty and doesn't change the way my objects are designed. It does not prevent a mistake from being made, but it will help you catch them.

so... how does it work?

Simple. All you have to do is add an Attribute to a property. This attribute has a custom property drawer that will color the field and add a tooltip.

In the image above I have define 2 classes and an interface. Here they are:

ExampleUsageBehaviour class

This class has the two properties that desire an object of type IExample but will still accept any MonoBehaviour. The IExample interface is defined at the top of this file.

using UnityEngine;
using CatchCo;

// define an interface
public interface IExample {}

public class ExampleUsageBehaviour : MonoBehaviour
  // note the typeof(IExample) in the next line.
  public MonoBehaviour MyIExampleBehaviour;
  // ditto
  public MonoBehaviour My2ndIExampleBehaviour;
IExample Shunner

This class does not inherit from IExample

using UnityEngine;

public class IsNotIExample : MonoBehaviour { }
IExample Implementor

This class does inherit from IExample and will not turn the Inspector red.

using UnityEngine;

public class IsIExample : MonoBehaviour, IExample { }

The result is the picture above.

where was the code again?

Download the code here

Brandon Catcho

Senior Software Engineer at TechSmith Corporation. I write/record music and explore game development on the side. All views expressed here are my own.

Lansing Michigan