Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

What's the point of all this?

The InspectorTypeEnforcerAttribute and the InspectorTypeEnforcerPropertyDrawer classes above will help inform you that a Monobehaviour does not implement a desired interface.

How to install

  • InspectorTypeEnforcerAttribute.cs - Put this file in your 'Scripts' folder
  • InspectorTypeEnforcerPropertyDrawer.cs - Put this in your 'Editor' folder

How to Use

Throw the [InspectorTypeEnforcer(typeof(YOUR_TYPE_HERE))] attribute on any Serialized property of a MonoBehaviour/ScriptableObject. See the 'TestUsageBehaviour.cs' below for an example.

The Result

Dragging a MonoBehaviour that does not implement the desired interface will turn red when dragged on to the property donned with the attribute.

using UnityEngine;
using System;
namespace CatchCo
{
public class InspectorTypeEnforcerAttribute : PropertyAttribute
{
public Type EnforcedType;
public InspectorTypeEnforcerAttribute(Type enforcedType)
{
EnforcedType = enforcedType;
}
}
}
using UnityEngine;
using UnityEditor;
using System;
using CatchCo;
namespace CatchCo
{
[CustomPropertyDrawer(typeof(InspectorTypeEnforcerAttribute))]
public class InspectorTypeEnforcerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// save the color temporarily
var tempColor = GUI.color;
var enforcedType = ((InspectorTypeEnforcerAttribute)attribute).EnforcedType;
if (property.objectReferenceValue != null && !enforcedType.IsInstanceOfType(property.objectReferenceValue))
{
GUI.color = Color.red;
label.text = "!! " + label.text;
if (string.IsNullOrEmpty(label.tooltip))
{
label.tooltip = "Error: Object does not implement/inherit from Type: " + enforcedType.Name;
}
}
else if (!string.IsNullOrEmpty(label.tooltip))
{
label.tooltip = string.Empty;
}
EditorGUI.PropertyField(position, property, label);
// reset color
GUI.color = tempColor;
}
}
}
using UnityEngine;
using System.Collections.Generic;
namespace CatchCo
{
public class TestUsageBehaviour : MonoBehaviour
{
[InspectorTypeEnforcer(typeof(ITestInterface))]
public MonoBehaviour TestProperty;
}
public interface ITestInterface
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment