1+ #if UNITY_2019_3_OR_NEWER
2+ using UnityEditor ;
3+ using UnityEngine ;
4+
5+ namespace MackySoft . SerializeReferenceExtensions . Editor
6+ {
7+ public static class CopyAndPasteProperty
8+ {
9+
10+ const string kCopiedPropertyPathKey = "SerializeReferenceExtensions.CopiedPropertyPath" ;
11+ const string kClipboardKey = "SerializeReferenceExtensions.CopyAndPasteProperty" ;
12+
13+ static readonly GUIContent kPasteContent = new GUIContent ( "Paste Property" ) ;
14+
15+ [ InitializeOnLoadMethod ]
16+ static void Initialize ( )
17+ {
18+ EditorApplication . contextualPropertyMenu += OnContextualPropertyMenu ;
19+ }
20+
21+ static void OnContextualPropertyMenu ( GenericMenu menu , SerializedProperty property )
22+ {
23+ if ( property . propertyType == SerializedPropertyType . ManagedReference )
24+ {
25+ // NOTE: When the callback function is called, the SerializedProperty is rewritten to the property that was being moused over at the time,
26+ // so a new SerializedProperty instance must be created.
27+ SerializedProperty clonedProperty = property . Copy ( ) ;
28+
29+ menu . AddItem ( new GUIContent ( $ "Copy \" { property . propertyPath } \" property") , false , Copy , clonedProperty ) ;
30+
31+ string copiedPropertyPath = SessionState . GetString ( kCopiedPropertyPathKey , string . Empty ) ;
32+ if ( ! string . IsNullOrEmpty ( copiedPropertyPath ) )
33+ {
34+ menu . AddItem ( new GUIContent ( $ "Paste \" { copiedPropertyPath } \" property") , false , Paste , clonedProperty ) ;
35+ }
36+ else
37+ {
38+ menu . AddDisabledItem ( kPasteContent ) ;
39+ }
40+ }
41+ }
42+
43+ static void Copy ( object customData )
44+ {
45+ SerializedProperty property = ( SerializedProperty ) customData ;
46+ string json = JsonUtility . ToJson ( property . managedReferenceValue ) ;
47+ SessionState . SetString ( kCopiedPropertyPathKey , property . propertyPath ) ;
48+ SessionState . SetString ( kClipboardKey , json ) ;
49+ }
50+
51+ static void Paste ( object customData )
52+ {
53+ SerializedProperty property = ( SerializedProperty ) customData ;
54+ string json = SessionState . GetString ( kClipboardKey , string . Empty ) ;
55+ if ( string . IsNullOrEmpty ( json ) )
56+ {
57+ return ;
58+ }
59+
60+ Undo . RecordObject ( property . serializedObject . targetObject , "Paste Property" ) ;
61+ JsonUtility . FromJsonOverwrite ( json , property . managedReferenceValue ) ;
62+ property . serializedObject . ApplyModifiedProperties ( ) ;
63+ }
64+ }
65+ }
66+ #endif
0 commit comments