diff --git a/Editor/Drawers/RawReferenceDrawer.cs b/Editor/Drawers/RawReferenceDrawer.cs index 72fa6e7..c11b9bf 100644 --- a/Editor/Drawers/RawReferenceDrawer.cs +++ b/Editor/Drawers/RawReferenceDrawer.cs @@ -11,6 +11,9 @@ internal class RawReferenceDrawer : ReferenceDrawer, IReferenceDrawer private readonly GUIContent label; private readonly FieldInfo fieldInfo; + private static object previousReferenceValue; + private static string previousPropertyPath; + private object RawReferenceValue { get @@ -21,6 +24,15 @@ private object RawReferenceValue ISerializableInterface instance = (ISerializableInterface)fieldInfo.GetValue(Property.serializedObject.targetObject); return instance.GetRawReference(); +#endif + } + + set + { +#if UNITY_2021_1_OR_NEWER + RawReferenceProperty.managedReferenceValue = value; +#else + fieldInfo.SetValue(Property.serializedObject.targetObject, value); #endif } } @@ -47,6 +59,8 @@ public float GetHeight() /// public void OnGUI(Rect position) { + AvoidDuplicateReferencesInArray(); + Rect objectFieldRect = new Rect(position) { height = EditorGUIUtility.singleLineHeight @@ -71,6 +85,8 @@ public void OnGUI(Rect position) true); HandleDragAndDrop(objectFieldRect); + + previousPropertyPath = Property.propertyPath; } /// @@ -91,5 +107,41 @@ protected override void OnPropertiesClicked() } } } + + private void AvoidDuplicateReferencesInArray() + { + if (!IsPropertyInArray(Property)) + return; + if (previousPropertyPath == null) + return; + if (previousPropertyPath == Property.propertyPath) + return; + + SerializedProperty rawReferenceProperty = Property.FindPropertyRelative("rawReference"); + object currentReferenceValue = RawReferenceValue; + + if (currentReferenceValue == null) + return; + + if (previousReferenceValue == currentReferenceValue) + { + RawReferenceValue = CreateInstance(currentReferenceValue); + rawReferenceProperty.serializedObject.ApplyModifiedProperties(); + } + + previousReferenceValue = currentReferenceValue; + } + + private static bool IsPropertyInArray(SerializedProperty prop) + { + return prop.propertyPath.Contains(".Array.data["); + } + + private static object CreateInstance(object source) + { + object instance = Activator.CreateInstance(source.GetType()); + EditorUtility.CopySerializedManagedFieldsOnly(source, instance); + return instance; + } } } diff --git a/Editor/SerializableInterfacePropertyDrawer.cs b/Editor/SerializableInterfacePropertyDrawer.cs index 7ce4953..e71019a 100644 --- a/Editor/SerializableInterfacePropertyDrawer.cs +++ b/Editor/SerializableInterfacePropertyDrawer.cs @@ -16,10 +16,7 @@ internal sealed class SerializableInterfacePropertyDrawer : PropertyDrawer private IReferenceDrawer activeDrawer; /// - public override bool CanCacheInspectorGUI(SerializedProperty property) - { - return false; - } + public override bool CanCacheInspectorGUI(SerializedProperty property) => false; private void Initialize(SerializedProperty property) {