-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathEasyEventEditor.cs
executable file
·1611 lines (1301 loc) · 64.4 KB
/
EasyEventEditor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MIT License
*
* Copyright (c) 2019 Merlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Script to make working with objects that have Unity persistent events easier.
*
* Allows five things that the default Unity event editor does not:
*
* 1. Allows reordering of events. If you want to reorder events in the default Unity editor, you need to delete events and recreate them in the desired order
* 2. Gives easy access to private methods and properties on the target object. Usually you'd otherwise need to edit the event in debug view to add private references.
* 3. Gives access to multiple components of the same type on the same object
* 4. Gives an Invoke button to execute the event in editor for debugging and testing
* 5. Adds hotkeys to event operations
*/
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Events;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Merlin
{
[InitializeOnLoad]
public class EasyEventEditorHandler
{
private const string eeeOverrideEventDrawerKey = "EEE.overrideEventDrawer";
private const string eeeShowPrivateMembersKey = "EEE.showPrivateMembers";
private const string eeeShowInvokeFieldKey = "EEE.showInvokeField";
private const string eeeDisplayArgumentTypeKey = "EEE.displayArgumentType";
private const string eeeGroupSameComponentTypeKey = "EEE.groupSameComponentType";
private const string eeeUseHotkeys = "EEE.usehotkeys";
private static bool patchApplied = false;
private static FieldInfo internalDrawerTypeMap = null;
private static System.Type attributeUtilityType = null;
public class EEESettings
{
public bool overrideEventDrawer;
public bool showPrivateMembers;
public bool showInvokeField;
public bool displayArgumentType;
public bool groupSameComponentType;
public bool useHotkeys;
}
// https://stackoverflow.com/questions/12898282/type-gettype-not-working
public static System.Type FindTypeInAllAssemblies(string qualifiedTypeName)
{
System.Type t = System.Type.GetType(qualifiedTypeName);
if (t != null)
{
return t;
}
else
{
foreach (System.Reflection.Assembly asm in System.AppDomain.CurrentDomain.GetAssemblies())
{
t = asm.GetType(qualifiedTypeName);
if (t != null)
return t;
}
return null;
}
}
static EasyEventEditorHandler()
{
EditorApplication.update += OnEditorUpdate;
}
static void OnEditorUpdate()
{
ApplyEventPropertyDrawerPatch();
}
[UnityEditor.Callbacks.DidReloadScripts]
private static void OnScriptsReloaded()
{
ApplyEventPropertyDrawerPatch();
}
internal static FieldInfo GetDrawerTypeMap()
{
// We already have the map so skip all the reflection
if (internalDrawerTypeMap != null)
{
return internalDrawerTypeMap;
}
System.Type scriptAttributeUtilityType = FindTypeInAllAssemblies("UnityEditor.ScriptAttributeUtility");
if (scriptAttributeUtilityType == null)
{
Debug.LogError("Could not find ScriptAttributeUtility in assemblies!");
return null;
}
// Save for later in case we need to lookup the function to populate the attributes
attributeUtilityType = scriptAttributeUtilityType;
FieldInfo info = scriptAttributeUtilityType.GetField("s_DrawerTypeForType", BindingFlags.NonPublic | BindingFlags.Static);
if (info == null)
{
Debug.LogError("Could not find drawer type map!");
return null;
}
internalDrawerTypeMap = info;
return internalDrawerTypeMap;
}
private static void ClearPropertyCaches()
{
if (attributeUtilityType == null)
{
Debug.LogError("UnityEditor.ScriptAttributeUtility type is null! Make sure you have called GetDrawerTypeMap() to ensure this is cached!");
return;
}
// Nuke handle caches so they can find our modified drawer
MethodInfo clearCacheFunc = attributeUtilityType.GetMethod("ClearGlobalCache", BindingFlags.NonPublic | BindingFlags.Static);
if (clearCacheFunc == null)
{
Debug.LogError("Could not find cache clear method!");
return;
}
clearCacheFunc.Invoke(null, new object[] { });
FieldInfo currentCacheField = attributeUtilityType.GetField("s_CurrentCache", BindingFlags.NonPublic | BindingFlags.Static);
if (currentCacheField == null)
{
Debug.LogError("Could not find CurrentCache field!");
return;
}
object currentCacheValue = currentCacheField.GetValue(null);
if (currentCacheValue != null)
{
MethodInfo clearMethod = currentCacheValue.GetType().GetMethod("Clear", BindingFlags.Public | BindingFlags.Instance);
if (clearMethod == null)
{
Debug.LogError("Could not find clear function for current cache!");
return;
}
clearMethod.Invoke(currentCacheValue, new object[] { });
}
System.Type inspectorWindowType = FindTypeInAllAssemblies("UnityEditor.InspectorWindow");
if (inspectorWindowType == null)
{
Debug.LogError("Could not find inspector window type!");
return;
}
FieldInfo trackerField = inspectorWindowType.GetField("m_Tracker", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo propertyHandleCacheField = typeof(Editor).GetField("m_PropertyHandlerCache", BindingFlags.NonPublic | BindingFlags.Instance);
if (trackerField == null || propertyHandleCacheField == null)
{
Debug.LogError("Could not find tracker field!");
return;
}
//FieldInfo trackerEditorsField = trackerField.GetType().GetField("")
System.Type propertyHandlerCacheType = FindTypeInAllAssemblies("UnityEditor.PropertyHandlerCache");
if (propertyHandlerCacheType == null)
{
Debug.LogError("Could not find type of PropertyHandlerCache");
return;
}
// Secondary nuke because Unity is great and keeps a cached copy of the events for every Editor in addition to a global cache we cleared earlier.
EditorWindow[] editorWindows = Resources.FindObjectsOfTypeAll<EditorWindow>();
foreach (EditorWindow editor in editorWindows)
{
if (editor.GetType() == inspectorWindowType || editor.GetType().IsSubclassOf(inspectorWindowType))
{
ActiveEditorTracker activeEditorTracker = trackerField.GetValue(editor) as ActiveEditorTracker;
if (activeEditorTracker != null)
{
foreach (Editor activeEditor in activeEditorTracker.activeEditors)
{
if (activeEditor != null)
{
propertyHandleCacheField.SetValue(activeEditor, System.Activator.CreateInstance(propertyHandlerCacheType));
activeEditor.Repaint(); // Force repaint to get updated drawing of property
}
}
}
}
}
}
// Applies patch to Unity's builtin tracking for Drawers to redirect any drawers for Unity Events to our EasyEventDrawer instead.
private static void ApplyEventDrawerPatch(bool enableOverride)
{
// Call here to find the scriptAttributeUtilityType in case it's needed for when overrides are disabled
FieldInfo drawerTypeMap = GetDrawerTypeMap();
if (enableOverride)
{
System.Type[] mapArgs = drawerTypeMap.FieldType.GetGenericArguments();
System.Type keyType = mapArgs[0];
System.Type valType = mapArgs[1];
if (keyType == null || valType == null)
{
Debug.LogError("Could not retrieve dictionary types!");
return;
}
FieldInfo drawerField = valType.GetField("drawer", BindingFlags.Public | BindingFlags.Instance);
FieldInfo typeField = valType.GetField("type", BindingFlags.Public | BindingFlags.Instance);
if (drawerField == null || typeField == null)
{
Debug.LogError("Could not retrieve dictionary value fields!");
return;
}
IDictionary drawerTypeMapDict = drawerTypeMap.GetValue(null) as IDictionary;
if (drawerTypeMapDict == null)
{
MethodInfo popAttributesFunc = attributeUtilityType.GetMethod("BuildDrawerTypeForTypeDictionary", BindingFlags.NonPublic | BindingFlags.Static);
if (popAttributesFunc == null)
{
Debug.LogError("Could not populate attributes for override!");
return;
}
popAttributesFunc.Invoke(null, new object[] { });
// Try again now that this should be populated
drawerTypeMapDict = drawerTypeMap.GetValue(null) as IDictionary;
if (drawerTypeMapDict == null)
{
Debug.LogError("Could not get dictionary for drawer types!");
return;
}
}
// Replace EventDrawer handles with our custom drawer
List<object> keysToRecreate = new List<object>();
foreach (DictionaryEntry entry in drawerTypeMapDict)
{
System.Type drawerType = (System.Type)drawerField.GetValue(entry.Value);
if (drawerType.Name == "UnityEventDrawer")
{
keysToRecreate.Add(entry.Key);
}
}
foreach (object keyToKill in keysToRecreate)
{
drawerTypeMapDict.Remove(keyToKill);
}
// Recreate these key-value pairs since they are structs
foreach (object keyToRecreate in keysToRecreate)
{
object newValMapping = System.Activator.CreateInstance(valType);
typeField.SetValue(newValMapping, (System.Type)keyToRecreate);
drawerField.SetValue(newValMapping, typeof(EasyEventEditorDrawer));
drawerTypeMapDict.Add(keyToRecreate, newValMapping);
}
}
else
{
MethodInfo popAttributesFunc = attributeUtilityType.GetMethod("BuildDrawerTypeForTypeDictionary", BindingFlags.NonPublic | BindingFlags.Static);
if (popAttributesFunc == null)
{
Debug.LogError("Could not populate attributes for override!");
return;
}
// Just force the editor to repopulate the drawers without nuking afterwards.
popAttributesFunc.Invoke(null, new object[] { });
}
// Clear caches to force event drawers to refresh immediately.
ClearPropertyCaches();
}
public static void ApplyEventPropertyDrawerPatch(bool forceApply = false)
{
EEESettings settings = GetEditorSettings();
if (!patchApplied || forceApply)
{
ApplyEventDrawerPatch(settings.overrideEventDrawer);
patchApplied = true;
}
}
public static EEESettings GetEditorSettings()
{
EEESettings settings = new EEESettings
{
overrideEventDrawer = EditorPrefs.GetBool(eeeOverrideEventDrawerKey, true),
showPrivateMembers = EditorPrefs.GetBool(eeeShowPrivateMembersKey, true),
showInvokeField = EditorPrefs.GetBool(eeeShowInvokeFieldKey, true),
displayArgumentType = EditorPrefs.GetBool(eeeDisplayArgumentTypeKey, true),
groupSameComponentType = EditorPrefs.GetBool(eeeGroupSameComponentTypeKey, false),
useHotkeys = EditorPrefs.GetBool(eeeUseHotkeys, true),
};
return settings;
}
public static void SetEditorSettings(EEESettings settings)
{
EditorPrefs.SetBool(eeeOverrideEventDrawerKey, settings.overrideEventDrawer);
EditorPrefs.SetBool(eeeShowPrivateMembersKey, settings.showPrivateMembers);
EditorPrefs.SetBool(eeeShowInvokeFieldKey, settings.showInvokeField);
EditorPrefs.SetBool(eeeDisplayArgumentTypeKey, settings.displayArgumentType);
EditorPrefs.SetBool(eeeGroupSameComponentTypeKey, settings.groupSameComponentType);
EditorPrefs.SetBool(eeeUseHotkeys, settings.useHotkeys);
}
}
internal class SettingsGUIContent
{
private static GUIContent enableToggleGuiContent = new GUIContent("Enable Easy Event Editor", "Replaces the default Unity event editing context with EEE");
private static GUIContent enablePrivateMembersGuiContent = new GUIContent("Show private properties and methods", "Exposes private/internal/obsolete properties and methods to the function list on events");
private static GUIContent showInvokeFieldGuiContent = new GUIContent("Show invoke button on events", "Gives you a button on events that can be clicked to execute all functions on a given event");
private static GUIContent displayArgumentTypeContent = new GUIContent("Display argument type on function name", "Shows the argument that a function takes on the function header");
private static GUIContent groupSameComponentTypeContent = new GUIContent("Do not group components of the same type", "If you have multiple components of the same type on one object, show all components. Unity hides duplicate components by default.");
private static GUIContent useHotkeys = new GUIContent("Use hotkeys", "Adds common Unity hotkeys to event editor that operate on the currently selected event. The commands are Add (CTRL+A), Copy, Paste, Cut, Delete, and Duplicate");
public static void DrawSettingsButtons(EasyEventEditorHandler.EEESettings settings)
{
EditorGUI.indentLevel += 1;
settings.overrideEventDrawer = EditorGUILayout.ToggleLeft(enableToggleGuiContent, settings.overrideEventDrawer);
EditorGUI.BeginDisabledGroup(!settings.overrideEventDrawer);
settings.showPrivateMembers = EditorGUILayout.ToggleLeft(enablePrivateMembersGuiContent, settings.showPrivateMembers);
settings.showInvokeField = EditorGUILayout.ToggleLeft(showInvokeFieldGuiContent, settings.showInvokeField);
settings.displayArgumentType = EditorGUILayout.ToggleLeft(displayArgumentTypeContent, settings.displayArgumentType);
settings.groupSameComponentType = !EditorGUILayout.ToggleLeft(groupSameComponentTypeContent, !settings.groupSameComponentType);
settings.useHotkeys = EditorGUILayout.ToggleLeft(useHotkeys, settings.useHotkeys);
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel -= 1;
}
}
#if UNITY_2018_3_OR_NEWER
// Use the new settings provider class instead so we don't need to add extra stuff to the Edit menu
// Using the IMGUI method
static class EasyEventEditorSettingsProvider
{
[SettingsProvider]
public static SettingsProvider CreateSettingsProvider()
{
var provider = new SettingsProvider("Preferences/Easy Event Editor", SettingsScope.User)
{
label = "Easy Event Editor",
guiHandler = (searchContext) =>
{
EasyEventEditorHandler.EEESettings settings = EasyEventEditorHandler.GetEditorSettings();
EditorGUI.BeginChangeCheck();
SettingsGUIContent.DrawSettingsButtons(settings);
if (EditorGUI.EndChangeCheck())
{
EasyEventEditorHandler.SetEditorSettings(settings);
EasyEventEditorHandler.ApplyEventPropertyDrawerPatch(true);
}
},
keywords = new HashSet<string>(new[] { "Easy", "Event", "Editor", "Delegate", "VRChat", "EEE" })
};
return provider;
}
}
#else
public class EasyEventEditorSettings : EditorWindow
{
[MenuItem("Edit/Easy Event Editor Settings")]
static void Init()
{
EasyEventEditorSettings window = GetWindow<EasyEventEditorSettings>(false, "EEE Settings");
window.minSize = new Vector2(350, 150);
window.maxSize = new Vector2(350, 150);
window.Show();
}
private void OnGUI()
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Easy Event Editor Settings", EditorStyles.boldLabel);
EditorGUILayout.Space();
EasyEventEditorHandler.EEESettings settings = EasyEventEditorHandler.GetEditorSettings();
EditorGUI.BeginChangeCheck();
SettingsGUIContent.DrawSettingsButtons(settings);
if (EditorGUI.EndChangeCheck())
{
EasyEventEditorHandler.SetEditorSettings(settings);
EasyEventEditorHandler.ApplyEventPropertyDrawerPatch(true);
}
}
}
#endif
// Drawer that gets patched in over Unity's default event drawer
public class EasyEventEditorDrawer : PropertyDrawer
{
class DrawerState
{
public ReorderableList reorderableList;
public int lastSelectedIndex;
// Invoke field tracking
public string currentInvokeStrArg = "";
public int currentInvokeIntArg = 0;
public float currentInvokeFloatArg = 0f;
public bool currentInvokeBoolArg = false;
public Object currentInvokeObjectArg = null;
}
class FunctionData
{
public FunctionData(SerializedProperty listener, Object target = null, MethodInfo method = null, PersistentListenerMode mode = PersistentListenerMode.EventDefined)
{
listenerElement = listener;
targetObject = target;
targetMethod = method;
listenerMode = mode;
}
public SerializedProperty listenerElement;
public Object targetObject;
public MethodInfo targetMethod;
public PersistentListenerMode listenerMode;
}
Dictionary<string, DrawerState> drawerStates = new Dictionary<string, DrawerState>();
DrawerState currentState;
string currentLabelText;
SerializedProperty currentProperty;
SerializedProperty listenerArray;
UnityEventBase dummyEvent;
MethodInfo cachedFindMethodInfo = null;
static EasyEventEditorHandler.EEESettings cachedSettings;
#if UNITY_2018_4_OR_NEWER
private static UnityEventBase GetDummyEventStep(string propertyPath, System.Type propertyType, BindingFlags bindingFlags)
{
UnityEventBase dummyEvent = null;
while (propertyPath.Length > 0)
{
if (propertyPath.StartsWith("."))
propertyPath = propertyPath.Substring(1);
string[] splitPath = propertyPath.Split(new char[] { '.' }, 2);
FieldInfo newField = propertyType.GetField(splitPath[0], bindingFlags);
if (newField == null)
break;
propertyType = newField.FieldType;
if (propertyType.IsArray)
{
propertyType = propertyType.GetElementType();
}
else if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
if (splitPath.Length == 1)
break;
propertyPath = splitPath[1];
if (propertyPath.StartsWith("Array.data["))
propertyPath = propertyPath.Split(new char[] { ']' }, 2)[1];
}
if (propertyType.IsSubclassOf(typeof(UnityEventBase)))
dummyEvent = System.Activator.CreateInstance(propertyType) as UnityEventBase;
return dummyEvent;
}
private static UnityEventBase GetDummyEvent(SerializedProperty property)
{
Object targetObject = property.serializedObject.targetObject;
if (targetObject == null)
return new UnityEvent();
UnityEventBase dummyEvent = null;
System.Type targetType = targetObject.GetType();
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
do
{
dummyEvent = GetDummyEventStep(property.propertyPath, targetType, bindingFlags);
bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
targetType = targetType.BaseType;
} while (dummyEvent == null && targetType != null);
return dummyEvent ?? new UnityEvent();
}
#endif
private void PrepareState(SerializedProperty propertyForState)
{
DrawerState state;
if (!drawerStates.TryGetValue(propertyForState.propertyPath, out state))
{
state = new DrawerState();
SerializedProperty persistentListeners = propertyForState.FindPropertyRelative("m_PersistentCalls.m_Calls");
// The fun thing is that if Unity just made the first bool arg true internally, this whole thing would be unnecessary.
state.reorderableList = new ReorderableList(propertyForState.serializedObject, persistentListeners, true, true, true, true);
state.reorderableList.elementHeight = 43; // todo: actually find proper constant for this.
state.reorderableList.drawHeaderCallback += DrawHeaderCallback;
state.reorderableList.drawElementCallback += DrawElementCallback;
state.reorderableList.onSelectCallback += SelectCallback;
state.reorderableList.onRemoveCallback += ReorderCallback;
state.reorderableList.onAddCallback += AddEventListener;
state.reorderableList.onRemoveCallback += RemoveCallback;
state.lastSelectedIndex = 0;
drawerStates.Add(propertyForState.propertyPath, state);
}
currentProperty = propertyForState;
currentState = state;
currentState.reorderableList.index = currentState.lastSelectedIndex;
listenerArray = state.reorderableList.serializedProperty;
// Setup dummy event
#if UNITY_2018_4_OR_NEWER
dummyEvent = GetDummyEvent(propertyForState);
#else
string eventTypeName = currentProperty.FindPropertyRelative("m_TypeName").stringValue;
System.Type eventType = EasyEventEditorHandler.FindTypeInAllAssemblies(eventTypeName);
if (eventType == null)
dummyEvent = new UnityEvent();
else
dummyEvent = System.Activator.CreateInstance(eventType) as UnityEventBase;
#endif
cachedSettings = EasyEventEditorHandler.GetEditorSettings();
}
private void HandleKeyboardShortcuts()
{
if (!cachedSettings.useHotkeys)
return;
Event currentEvent = Event.current;
if (!currentState.reorderableList.HasKeyboardControl())
return;
if (currentEvent.type == EventType.ValidateCommand)
{
if (currentEvent.commandName == "Copy" ||
currentEvent.commandName == "Paste" ||
currentEvent.commandName == "Cut" ||
currentEvent.commandName == "Duplicate" ||
currentEvent.commandName == "Delete" ||
currentEvent.commandName == "SoftDelete" ||
currentEvent.commandName == "SelectAll")
{
currentEvent.Use();
}
}
else if (currentEvent.type == EventType.ExecuteCommand)
{
if (currentEvent.commandName == "Copy")
{
HandleCopy();
currentEvent.Use();
}
else if (currentEvent.commandName == "Paste")
{
HandlePaste();
currentEvent.Use();
}
else if (currentEvent.commandName == "Cut")
{
HandleCut();
currentEvent.Use();
}
else if (currentEvent.commandName == "Duplicate")
{
HandleDuplicate();
currentEvent.Use();
}
else if (currentEvent.commandName == "Delete" || currentEvent.commandName == "SoftDelete")
{
RemoveCallback(currentState.reorderableList);
currentEvent.Use();
}
else if (currentEvent.commandName == "SelectAll") // Use Ctrl+A for add, since Ctrl+N isn't usable using command names
{
HandleAdd();
currentEvent.Use();
}
}
}
private class EventClipboardStorage
{
public static SerializedObject CopiedEventProperty;
public static int CopiedEventIndex;
}
private void HandleCopy()
{
SerializedObject serializedEvent = new SerializedObject(listenerArray.GetArrayElementAtIndex(currentState.reorderableList.index).serializedObject.targetObject);
EventClipboardStorage.CopiedEventProperty = serializedEvent;
EventClipboardStorage.CopiedEventIndex = currentState.reorderableList.index;
}
private void HandlePaste()
{
if (EventClipboardStorage.CopiedEventProperty == null)
return;
SerializedProperty iterator = EventClipboardStorage.CopiedEventProperty.GetIterator();
if (iterator == null)
return;
while (iterator.NextVisible(true))
{
if (iterator != null && iterator.name == "m_PersistentCalls")
{
iterator = iterator.FindPropertyRelative("m_Calls");
break;
}
}
if (iterator.arraySize < (EventClipboardStorage.CopiedEventIndex + 1))
return;
SerializedProperty sourceProperty = iterator.GetArrayElementAtIndex(EventClipboardStorage.CopiedEventIndex);
if (sourceProperty == null)
return;
int targetArrayIdx = currentState.reorderableList.count > 0 ? currentState.reorderableList.index : 0;
currentState.reorderableList.serializedProperty.InsertArrayElementAtIndex(targetArrayIdx);
SerializedProperty targetProperty = currentState.reorderableList.serializedProperty.GetArrayElementAtIndex((currentState.reorderableList.count > 0 ? currentState.reorderableList.index : 0) + 1);
ResetEventState(targetProperty);
targetProperty.FindPropertyRelative("m_CallState").enumValueIndex = sourceProperty.FindPropertyRelative("m_CallState").enumValueIndex;
targetProperty.FindPropertyRelative("m_Target").objectReferenceValue = sourceProperty.FindPropertyRelative("m_Target").objectReferenceValue;
targetProperty.FindPropertyRelative("m_MethodName").stringValue = sourceProperty.FindPropertyRelative("m_MethodName").stringValue;
targetProperty.FindPropertyRelative("m_Mode").enumValueIndex = sourceProperty.FindPropertyRelative("m_Mode").enumValueIndex;
SerializedProperty targetArgs = targetProperty.FindPropertyRelative("m_Arguments");
SerializedProperty sourceArgs = sourceProperty.FindPropertyRelative("m_Arguments");
targetArgs.FindPropertyRelative("m_IntArgument").intValue = sourceArgs.FindPropertyRelative("m_IntArgument").intValue;
targetArgs.FindPropertyRelative("m_FloatArgument").floatValue = sourceArgs.FindPropertyRelative("m_FloatArgument").floatValue;
targetArgs.FindPropertyRelative("m_BoolArgument").boolValue = sourceArgs.FindPropertyRelative("m_BoolArgument").boolValue;
targetArgs.FindPropertyRelative("m_StringArgument").stringValue = sourceArgs.FindPropertyRelative("m_StringArgument").stringValue;
targetArgs.FindPropertyRelative("m_ObjectArgument").objectReferenceValue = sourceArgs.FindPropertyRelative("m_ObjectArgument").objectReferenceValue;
targetArgs.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue = sourceArgs.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue;
currentState.reorderableList.index++;
currentState.lastSelectedIndex++;
targetProperty.serializedObject.ApplyModifiedProperties();
}
private void HandleCut()
{
HandleCopy();
RemoveCallback(currentState.reorderableList);
}
private void HandleDuplicate()
{
if (currentState.reorderableList.count == 0)
return;
SerializedProperty listProperty = currentState.reorderableList.serializedProperty;
SerializedProperty eventProperty = listProperty.GetArrayElementAtIndex(currentState.reorderableList.index);
eventProperty.DuplicateCommand();
currentState.reorderableList.index++;
currentState.lastSelectedIndex++;
}
private void HandleAdd()
{
int targetIdx = currentState.reorderableList.count > 0 ? currentState.reorderableList.index : 0;
currentState.reorderableList.serializedProperty.InsertArrayElementAtIndex(targetIdx);
SerializedProperty eventProperty = currentState.reorderableList.serializedProperty.GetArrayElementAtIndex(currentState.reorderableList.index + 1);
ResetEventState(eventProperty);
currentState.reorderableList.index++;
currentState.lastSelectedIndex++;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
currentLabelText = label.text;
PrepareState(property);
HandleKeyboardShortcuts();
if (dummyEvent == null)
return;
if (currentState.reorderableList != null)
{
int oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
currentState.reorderableList.DoList(position);
EditorGUI.indentLevel = oldIndent;
}
}
static void InvokeOnTargetEvents(MethodInfo method, object[] targets, object argValue)
{
foreach (object target in targets)
{
if (argValue != null)
method.Invoke(target, new object[] { argValue });
else
method.Invoke(target, new object[] { });
}
}
void DrawInvokeField(Rect position, float headerStartOffset)
{
Rect buttonPos = position;
buttonPos.height *= 0.9f;
buttonPos.width = 51;
buttonPos.x += headerStartOffset + 2;
Rect textPos = buttonPos;
textPos.x += 6;
textPos.width -= 12;
Rect inputFieldPos = position;
inputFieldPos.height = buttonPos.height;
inputFieldPos.width = position.width - buttonPos.width - 3 - headerStartOffset;
inputFieldPos.x = buttonPos.x + buttonPos.width + 2;
inputFieldPos.y += 1;
Rect inputFieldTextPlaceholder = inputFieldPos;
System.Type[] eventInvokeArgs = GetEventParams(dummyEvent);
GUIStyle textStyle = EditorStyles.miniLabel;
textStyle.alignment = TextAnchor.MiddleLeft;
MethodInfo invokeMethod = InvokeFindMethod("Invoke", dummyEvent, dummyEvent, PersistentListenerMode.EventDefined);
FieldInfo serializedField = currentProperty.serializedObject.targetObject.GetType().GetField(currentProperty.name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
object[] invokeTargets = currentProperty.serializedObject.targetObjects.Select(target => target == null || serializedField == null ? null : serializedField.GetValue(target)).Where(f => f != null).ToArray();
EditorGUI.BeginDisabledGroup(invokeTargets.Length == 0 || invokeMethod == null);
bool executeInvoke = GUI.Button(buttonPos, "", EditorStyles.miniButton);
GUI.Label(textPos, "Invoke"/* + " (" + string.Join(", ", eventInvokeArgs.Select(e => e.Name).ToArray()) + ")"*/, textStyle);
if (eventInvokeArgs.Length > 0)
{
System.Type argType = eventInvokeArgs[0];
if (argType == typeof(string))
{
currentState.currentInvokeStrArg = EditorGUI.TextField(inputFieldPos, currentState.currentInvokeStrArg);
// Draw placeholder text
if (currentState.currentInvokeStrArg.Length == 0)
{
GUIStyle placeholderLabelStyle = EditorStyles.centeredGreyMiniLabel;
placeholderLabelStyle.alignment = TextAnchor.UpperLeft;
GUI.Label(inputFieldTextPlaceholder, "String argument...", placeholderLabelStyle);
}
if (executeInvoke)
InvokeOnTargetEvents(invokeMethod, invokeTargets, currentState.currentInvokeStrArg);
}
else if (argType == typeof(int))
{
currentState.currentInvokeIntArg = EditorGUI.IntField(inputFieldPos, currentState.currentInvokeIntArg);
if (executeInvoke)
InvokeOnTargetEvents(invokeMethod, invokeTargets, currentState.currentInvokeIntArg);
}
else if (argType == typeof(float))
{
currentState.currentInvokeFloatArg = EditorGUI.FloatField(inputFieldPos, currentState.currentInvokeFloatArg);
if (executeInvoke)
InvokeOnTargetEvents(invokeMethod, invokeTargets, currentState.currentInvokeFloatArg);
}
else if (argType == typeof(bool))
{
currentState.currentInvokeBoolArg = EditorGUI.Toggle(inputFieldPos, currentState.currentInvokeBoolArg);
if (executeInvoke)
InvokeOnTargetEvents(invokeMethod, invokeTargets, currentState.currentInvokeBoolArg);
}
else if (argType == typeof(Object))
{
currentState.currentInvokeObjectArg = EditorGUI.ObjectField(inputFieldPos, currentState.currentInvokeObjectArg, argType, true);
if (executeInvoke)
invokeMethod.Invoke(currentProperty.serializedObject.targetObject, new object[] { currentState.currentInvokeObjectArg });
}
}
else if (executeInvoke) // No input arg
{
InvokeOnTargetEvents(invokeMethod, invokeTargets, null);
}
EditorGUI.EndDisabledGroup();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
PrepareState(property);
float height = 0f;
if (currentState.reorderableList != null)
height = currentState.reorderableList.GetHeight();
return height;
}
MethodInfo InvokeFindMethod(string functionName, object targetObject, UnityEventBase eventObject, PersistentListenerMode listenerMode, System.Type argType = null)
{
MethodInfo findMethod = cachedFindMethodInfo;
if (findMethod == null)
{
// Rather not reinvent the wheel considering this function calls different functions depending on the number of args the event has...
// Unity 2020.1 changed the function signature for the FindMethod method (the second parameter is a Type instead of an object)
findMethod = eventObject.GetType().GetMethod("FindMethod", BindingFlags.NonPublic | BindingFlags.Instance, null,
new System.Type[] {
typeof(string),
#if UNITY_2020_1_OR_NEWER
typeof(System.Type),
#else
typeof(object),
#endif
typeof(PersistentListenerMode),
typeof(System.Type)
},
null);
cachedFindMethodInfo = findMethod;
}
if (findMethod == null)
{
Debug.LogError("Could not find FindMethod function!");
return null;
}
#if UNITY_2020_1_OR_NEWER
return findMethod.Invoke(eventObject, new object[] {functionName, targetObject?.GetType(), listenerMode, argType }) as MethodInfo;
#else
return findMethod.Invoke(eventObject, new object[] {functionName, targetObject, listenerMode, argType }) as MethodInfo;
#endif
}
System.Type[] GetEventParams(UnityEventBase eventIn)
{
MethodInfo methodInfo = InvokeFindMethod("Invoke", eventIn, eventIn, PersistentListenerMode.EventDefined);
return methodInfo.GetParameters().Select(x => x.ParameterType).ToArray();
}
string GetEventParamsStr(UnityEventBase eventIn)
{
StringBuilder builder = new StringBuilder();
System.Type[] methodTypes = GetEventParams(eventIn);
builder.Append("(");
builder.Append(string.Join(", ", methodTypes.Select(val => val.Name).ToArray()));
builder.Append(")");
return builder.ToString();
}
string GetFunctionArgStr(string functionName, object targetObject, PersistentListenerMode listenerMode, System.Type argType = null)
{
MethodInfo methodInfo = InvokeFindMethod(functionName, targetObject, dummyEvent, listenerMode, argType);
if (methodInfo == null)
return "";
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length == 0)
return "";
return GetTypeName(parameterInfos[0].ParameterType);
}
void DrawHeaderCallback(Rect headerRect)
{
// We need to know where to position the invoke field based on the length of the title in the UI
GUIContent headerTitle = new GUIContent(string.IsNullOrEmpty(currentLabelText) ? "Event" : currentLabelText + " " + GetEventParamsStr(dummyEvent));
float headerStartOffset = EditorStyles.label.CalcSize(headerTitle).x;
GUI.Label(headerRect, headerTitle);
if (cachedSettings.showInvokeField)
DrawInvokeField(headerRect, headerStartOffset);
}
Rect[] GetElementRects(Rect rect)
{
Rect[] rects = new Rect[4];
rect.height = EditorGUIUtility.singleLineHeight;
rect.y += 2;
// enabled field
rects[0] = rect;
rects[0].width *= 0.3f;