Last active
May 16, 2020 11:10
-
-
Save ErnSur/d94c8a822109c793b853f108bde3501c to your computer and use it in GitHub Desktop.
[Unity] SerializedInterface 2020
This file contains 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
[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); | |
} | |
} |
This file contains 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 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