I was again looking for some weird ways to speed up my workflow in unity.
Most of us know that we are not able to reference interface implementations in the editor that easily. Nevertheless I found a solution that may not be the best out there but only needs two classes of less than 100 lines of code to work. All assets that inherit from UnityEngine.Object are supported.
That said, couldn’t it be possible to make Interface references serializable internally??
How does it work?
We use an object field to be able to assign any object but actually filter it with the interface we want.
In the inspector we can then drag and drop any UnityEngine.Object that implements the given interface (I haven’t got the object picker working yet). This means the window containing this field needs to stay open e.g. select GameObject > click three dots > select “Properties…”.
Then just navigate to the Object/Component you want to add and drag it to the slot
And that’s it. You can now access it through script. Only null checks are needed to prevent errors, no casts to other types!
The Code needed
InterfaceReference.cs
using UnityEngine;
[System.Serializable]
public class InterfaceReference<TInterface>
where TInterface : class
{
[SerializeField] Object m_Target;
public TInterface Target => m_Target as TInterface;
}
InterfaceReferencePropertyDrawer.cs
using System.Collections;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(InterfaceReference<>), true)]
public class InterfaceReferencePropertyDrawer : PropertyDrawer
{
SerializedProperty property_Target;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
property_Target = property.FindPropertyRelative("m_Target");
Rect rect = new(position.x, position.y, position.width, EditorGUI.GetPropertyHeight(property_Target));
EditorGUI.ObjectField(rect, property_Target, GetInterfaceType(), label);
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return base.GetPropertyHeight(property, label);
}
System.Type GetInterfaceType()
{
System.Type type = fieldInfo.FieldType;
System.Type[] typeArguments = type.GenericTypeArguments;
if (typeof(IEnumerable).IsAssignableFrom(type))
{
typeArguments = fieldInfo.FieldType.GenericTypeArguments[0].GenericTypeArguments;
}
if (typeArguments == null || typeArguments.Length == 0)
return null;
return typeArguments[0];
}
}
Example
IInteractable.cs
public interface IInteractable
{
void Interact();
}
Interactor.cs
using System.Collections.Generic;
using UnityEngine;
public class Interactor : MonoBehaviour
{
[SerializeField] List<InterfaceReference<IInteractable>> m_Interactables;
private void Awake()
{
foreach (var interactable in m_Interactables)
{
if (interactable == null)
continue;
interactable.Target.Interact();
}
}
}

