Skip to content

Instantly share code, notes, and snippets.

@paulhayes
Created July 9, 2018 11:01
Show Gist options
  • Save paulhayes/13395cf1b96a11d8b6ac1963e3498f8a to your computer and use it in GitHub Desktop.
Save paulhayes/13395cf1b96a11d8b6ac1963e3498f8a to your computer and use it in GitHub Desktop.
Really simple utility to allow you to reference UnityEngine.Objects but only of a particular type as inspector fields
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InterfaceObjectAttribute : PropertyAttribute
{
public Type type;
public InterfaceObjectAttribute(Type type){
this.type = type;
}
}
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(InterfaceObjectAttribute))]
public class RangeDrawer : PropertyDrawer
{
// Draw the property inside the given rect
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.ObjectField(position,property,label);
//base.OnGUI(position,property,label);
var obj = property.objectReferenceValue;
if(obj!=null && !IsMatchingInterface(obj)){
property.objectReferenceValue = null;
EditorUtility.SetDirty( property.serializedObject.targetObject );
}
}
bool IsMatchingInterface(UnityEngine.Object obj){
InterfaceObjectAttribute ioa = (InterfaceObjectAttribute)attribute;
return ioa.type.IsAssignableFrom(obj.GetType());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment