Skip to content

Require Interface Attribute

Paulo edited this page Jul 31, 2021 · 1 revision

Description

The Require Interface attribute allows for a serialized interface field in the inspector, however, it has some drawbacks. Take a look at the example below.

Usage

[SerializeField, RequireInterface(typeof(IExample))]
private Object interfaceImplementer;

private IInteractable Interface => (IExample) interfaceImplementer;

This will allow any object that implements the interface to be dragged into the field. This attribute, however, only provides a workaround, as true interface serialization in Unity is not supported. As you can see, you must create a field of type object, and then convert it to your desired interface through whatever mean you see fit.

Furthermore, you must actually perform a simple, albeit slightly inconvenient trick to drag your interface into the field; you must first create a second tab of the inspector, and drag the desired object from the second tab to the first tab that contains the field.

This field attribute is meant as a last resort, when using an abstract class instead of an interface is not possible.

Showcase

Showcase GIF

Clone this wiki locally