11// NOTE: managedReferenceValue getter is available only in Unity 2021.3 or later.
22#if UNITY_2021_3_OR_NEWER
3+ using System ;
34using UnityEditor ;
45using UnityEngine ;
56
67namespace MackySoft . SerializeReferenceExtensions . Editor
78{
8- public static class CopyAndPasteProperty
9+ public static class ManagedReferenceContextualPropertyMenu
910 {
1011
1112 const string kCopiedPropertyPathKey = "SerializeReferenceExtensions.CopiedPropertyPath" ;
1213 const string kClipboardKey = "SerializeReferenceExtensions.CopyAndPasteProperty" ;
1314
1415 static readonly GUIContent kPasteContent = new GUIContent ( "Paste Property" ) ;
16+ static readonly GUIContent kNewInstanceContent = new GUIContent ( "New Instance" ) ;
17+ static readonly GUIContent kResetAndNewInstanceContent = new GUIContent ( "Reset and New Instance" ) ;
1518
1619 [ InitializeOnLoadMethod ]
1720 static void Initialize ( )
@@ -38,6 +41,20 @@ static void OnContextualPropertyMenu (GenericMenu menu, SerializedProperty prope
3841 {
3942 menu . AddDisabledItem ( kPasteContent ) ;
4043 }
44+
45+ menu . AddSeparator ( "" ) ;
46+
47+ bool hasInstance = clonedProperty . managedReferenceValue != null ;
48+ if ( hasInstance )
49+ {
50+ menu . AddItem ( kNewInstanceContent , false , NewInstance , clonedProperty ) ;
51+ menu . AddItem ( kResetAndNewInstanceContent , false , ResetAndNewInstance , clonedProperty ) ;
52+ }
53+ else
54+ {
55+ menu . AddDisabledItem ( kNewInstanceContent ) ;
56+ menu . AddDisabledItem ( kResetAndNewInstanceContent ) ;
57+ }
4158 }
4259 }
4360
@@ -62,6 +79,29 @@ static void Paste (object customData)
6279 JsonUtility . FromJsonOverwrite ( json , property . managedReferenceValue ) ;
6380 property . serializedObject . ApplyModifiedProperties ( ) ;
6481 }
82+
83+ static void NewInstance ( object customData )
84+ {
85+ SerializedProperty property = ( SerializedProperty ) customData ;
86+ string json = JsonUtility . ToJson ( property . managedReferenceValue ) ;
87+
88+ Undo . RecordObject ( property . serializedObject . targetObject , "New Instance" ) ;
89+ property . managedReferenceValue = JsonUtility . FromJson ( json , property . managedReferenceValue . GetType ( ) ) ;
90+ property . serializedObject . ApplyModifiedProperties ( ) ;
91+
92+ Debug . Log ( $ "Create new instance of \" { property . propertyPath } \" .") ;
93+ }
94+
95+ static void ResetAndNewInstance ( object customData )
96+ {
97+ SerializedProperty property = ( SerializedProperty ) customData ;
98+
99+ Undo . RecordObject ( property . serializedObject . targetObject , "Reset and New Instance" ) ;
100+ property . managedReferenceValue = Activator . CreateInstance ( property . managedReferenceValue . GetType ( ) ) ;
101+ property . serializedObject . ApplyModifiedProperties ( ) ;
102+
103+ Debug . Log ( $ "Reset property and created new instance of \" { property . propertyPath } \" .") ;
104+ }
65105 }
66106}
67107#endif
0 commit comments