Skip to content

Commit

Permalink
Merge pull request #55 from mackysoft/feature/reset-reference
Browse files Browse the repository at this point in the history
Implement new instance context menu
  • Loading branch information
mackysoft committed Feb 17, 2024
2 parents e5627b1 + c141acf commit f275c46
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
// NOTE: managedReferenceValue getter is available only in Unity 2021.3 or later.
#if UNITY_2021_3_OR_NEWER
using System;
using UnityEditor;
using UnityEngine;

namespace MackySoft.SerializeReferenceExtensions.Editor
{
public static class CopyAndPasteProperty
public static class ManagedReferenceContextualPropertyMenu
{

const string kCopiedPropertyPathKey = "SerializeReferenceExtensions.CopiedPropertyPath";
const string kClipboardKey = "SerializeReferenceExtensions.CopyAndPasteProperty";

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]
static void Initialize ()
Expand All @@ -38,6 +41,20 @@ static void OnContextualPropertyMenu (GenericMenu menu, SerializedProperty prope
{
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);
}
}
}

Expand All @@ -62,6 +79,29 @@ static void Paste (object customData)
JsonUtility.FromJsonOverwrite(json, property.managedReferenceValue);
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

0 comments on commit f275c46

Please sign in to comment.