Obtaining references to Iinterfaces in Unity 3D

In Unity it is possible to get interface references calling GetComponent<T>()

Since it is possible for multiple scripts to implement a interface, I would always use GetComponents<T>().

For the example above you would call GetComponents<IDamageable>() and that will return all references to implementations of the interface at the root of the Game Object. You can cast the object to a interface and the other way around by calling >object< as >type<.

(flashOnHitComponent as IDamageable). You can find more information about casting here



The pattern I apply using interfaces in Unity 3D

Usually I create a script that is responsible for obtaining and notifying all interfaces on a object.

For example I wll use the Health component from Health Pro & Effects, which will get all health related interface references during editor-time.

Such as IKIllable, IDamageable, IReviveable. And during run-time it will notify all those components based on the implemented interfaces.

The benefit of this pattern is, I do not longer have to think about creating references for the Health script. No need for delegates, or UnityEvents.