I’m trying to implement a way to drag and drop interface in the editor:
public class AssignableTest : MonoBehaviour
{
[SerializeReference, Assignable] private IFoo foo;
}
I got close but ran into an error
[CustomPropertyDrawer(typeof(AssignableAttribute), true)]
public class AssignableDrawer : PropertyDrawer
{
private UnityEngine.Object rawObject;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (!fieldInfo.FieldType.IsInterface)
{
label.text = "AssignableAttribute can only be used on interfaces";
EditorGUI.LabelField(position, label.text);
}
Type interfaceType = fieldInfo.FieldType;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(fieldInfo.FieldType.Name);
rawObject = EditorGUILayout.ObjectField(rawObject, typeof(UnityEngine.Object), true);
if (rawObject is MonoBehaviour monoBehaviour)
{
var implementsCorrectInterface = monoBehaviour.GetType().GetInterface(interfaceType.Name) != null;
if (implementsCorrectInterface)
{
// ERROR: Cannot assign UnityEngine.Object to managedReferenceValue.
property.managedReferenceValue = monoBehaviour;
}
else
{
label.text = "MonoBehaviour does not implement the correct interface";
EditorGUI.LabelField(position, label.text);
}
}
EditorGUILayout.EndHorizontal();
}
}
The error message is “Cannot assign UnityEngine.Object to managedReferenceValue”.
I’m just wondering why this is? The reasons I’ve read is that UnityEngine.Objects are already serialized and thus don’t need to be supported. If it was supported though we could have drag and drop [SerializeReference] solving many issues. I’ll stick to Source Generators for now.