Created
July 9, 2018 11:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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