Skip to content

Instantly share code, notes, and snippets.

@ErnSur
Last active May 16, 2020 11:10
Show Gist options
  • Save ErnSur/d94c8a822109c793b853f108bde3501c to your computer and use it in GitHub Desktop.
Save ErnSur/d94c8a822109c793b853f108bde3501c to your computer and use it in GitHub Desktop.
[Unity] SerializedInterface 2020
[CustomPropertyDrawer(typeof(Object<>))]
public class SerializableInterfaceDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var serializedValueProperty = property.FindPropertyRelative("serializedValue");
var interfaceType = fieldInfo.FieldType.GetGenericArguments()[0];
serializedValueProperty.objectReferenceValue =
EditorGUI.ObjectField(position, label, serializedValueProperty.objectReferenceValue, interfaceType, true);
}
}
using UnityEngine;
using Object = UnityEngine.Object;
[System.Serializable]
public class Object<TInterface> where TInterface : class
{
[SerializeField]
private Object serializedValue;
private TInterface value = null;
public TInterface Value
{
get
{
if (value == null && serializedValue != null)
{
value = (TInterface)(object)serializedValue; // No memory allocation
}
return value;
}
set
{
serializedValue = (Object)(object)value;
this.value = null; // To trigger new caching for next get call
}
}
public static implicit operator TInterface(Object<TInterface> obj)
{
return obj.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment