Implement new instance menu

This commit is contained in:
Makihiro 2024-02-18 03:02:41 +09:00
parent 7f424c0f97
commit fdc0a286c8

View File

@ -1,5 +1,6 @@
// NOTE: managedReferenceValue getter is available only in Unity 2021.3 or later. // NOTE: managedReferenceValue getter is available only in Unity 2021.3 or later.
#if UNITY_2021_3_OR_NEWER #if UNITY_2021_3_OR_NEWER
using System;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
@ -12,6 +13,8 @@ namespace MackySoft.SerializeReferenceExtensions.Editor
const string kClipboardKey = "SerializeReferenceExtensions.CopyAndPasteProperty"; const string kClipboardKey = "SerializeReferenceExtensions.CopyAndPasteProperty";
static readonly GUIContent kPasteContent = new GUIContent("Paste Property"); static readonly GUIContent kPasteContent = new GUIContent("Paste Property");
static readonly GUIContent kNewInstanceContent = new GUIContent("New Instance");
static readonly GUIContent kResetAndNewInstanceContent = new GUIContent("Reset and New Instance");
[InitializeOnLoadMethod] [InitializeOnLoadMethod]
static void Initialize () static void Initialize ()
@ -38,6 +41,20 @@ namespace MackySoft.SerializeReferenceExtensions.Editor
{ {
menu.AddDisabledItem(kPasteContent); menu.AddDisabledItem(kPasteContent);
} }
menu.AddSeparator("");
bool hasInstance = clonedProperty.managedReferenceValue != null;
if (hasInstance)
{
menu.AddItem(kNewInstanceContent, false, NewInstance, clonedProperty);
menu.AddItem(kResetAndNewInstanceContent, false, ResetAndNewInstance, clonedProperty);
}
else
{
menu.AddDisabledItem(kNewInstanceContent);
menu.AddDisabledItem(kResetAndNewInstanceContent);
}
} }
} }
@ -62,6 +79,29 @@ namespace MackySoft.SerializeReferenceExtensions.Editor
JsonUtility.FromJsonOverwrite(json, property.managedReferenceValue); JsonUtility.FromJsonOverwrite(json, property.managedReferenceValue);
property.serializedObject.ApplyModifiedProperties(); property.serializedObject.ApplyModifiedProperties();
} }
static void NewInstance (object customData)
{
SerializedProperty property = (SerializedProperty)customData;
string json = JsonUtility.ToJson(property.managedReferenceValue);
Undo.RecordObject(property.serializedObject.targetObject, "New Instance");
property.managedReferenceValue = JsonUtility.FromJson(json, property.managedReferenceValue.GetType());
property.serializedObject.ApplyModifiedProperties();
Debug.Log($"Create new instance of \"{property.propertyPath}\".");
}
static void ResetAndNewInstance (object customData)
{
SerializedProperty property = (SerializedProperty)customData;
Undo.RecordObject(property.serializedObject.targetObject, "Reset and New Instance");
property.managedReferenceValue = Activator.CreateInstance(property.managedReferenceValue.GetType());
property.serializedObject.ApplyModifiedProperties();
Debug.Log($"Reset property and created new instance of \"{property.propertyPath}\".");
}
} }
} }
#endif #endif