forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityEvent.cs
More file actions
1168 lines (981 loc) · 42.2 KB
/
Copy pathUnityEvent.cs
File metadata and controls
1168 lines (981 loc) · 42.2 KB
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.Scripting;
using UnityEngine.Serialization;
namespace UnityEngine.Events
{
[Serializable]
public enum PersistentListenerMode
{
EventDefined,
Void,
Object,
Int,
Float,
String,
Bool
}
internal class UnityEventTools
{
// Fix for assembly type name containing version / culture. We don't care about this for UI.
// we need to fix this here, because there is old data in existing projects.
// Typically, we're looking for .net Assembly Qualified Type Names and stripping everything after '<namespaces>.<typename>, <assemblyname>'
// Example: System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' -> 'System.String, mscorlib'
internal static string TidyAssemblyTypeName(string assemblyTypeName)
{
if (string.IsNullOrEmpty(assemblyTypeName))
return assemblyTypeName;
int min = Int32.MaxValue;
int i = assemblyTypeName.IndexOf(", Version=");
if (i != -1)
min = Math.Min(i, min);
i = assemblyTypeName.IndexOf(", Culture=");
if (i != -1)
min = Math.Min(i, min);
i = assemblyTypeName.IndexOf(", PublicKeyToken=");
if (i != -1)
min = Math.Min(i, min);
if (min != Int32.MaxValue)
assemblyTypeName = assemblyTypeName.Substring(0, min);
// Strip module assembly name.
// The non-modular version will always work, due to type forwarders.
// This way, when a type gets moved to a differnet module, previously serialized UnityEvents still work.
i = assemblyTypeName.IndexOf(", UnityEngine.");
if (i != -1 && assemblyTypeName.EndsWith("Module"))
assemblyTypeName = assemblyTypeName.Substring(0, i) + ", UnityEngine";
return assemblyTypeName;
}
}
[Serializable]
class ArgumentCache : ISerializationCallbackReceiver
{
[FormerlySerializedAs("objectArgument")]
[SerializeField] private Object m_ObjectArgument;
[FormerlySerializedAs("objectArgumentAssemblyTypeName")]
[SerializeField] private string m_ObjectArgumentAssemblyTypeName;
[FormerlySerializedAs("intArgument")]
[SerializeField] private int m_IntArgument;
[FormerlySerializedAs("floatArgument")]
[SerializeField] private float m_FloatArgument;
[FormerlySerializedAs("stringArgument")]
[SerializeField] private string m_StringArgument;
[SerializeField] private bool m_BoolArgument;
public Object unityObjectArgument
{
get { return m_ObjectArgument; }
set
{
m_ObjectArgument = value;
m_ObjectArgumentAssemblyTypeName = value != null ? value.GetType().AssemblyQualifiedName : string.Empty;
}
}
public string unityObjectArgumentAssemblyTypeName
{
get { return m_ObjectArgumentAssemblyTypeName; }
}
public int intArgument { get { return m_IntArgument; } set { m_IntArgument = value; } }
public float floatArgument { get { return m_FloatArgument; } set { m_FloatArgument = value; } }
public string stringArgument { get { return m_StringArgument; } set { m_StringArgument = value; } }
public bool boolArgument { get { return m_BoolArgument; } set { m_BoolArgument = value; } }
public void OnBeforeSerialize()
{
m_ObjectArgumentAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_ObjectArgumentAssemblyTypeName);
}
public void OnAfterDeserialize()
{
m_ObjectArgumentAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_ObjectArgumentAssemblyTypeName);
}
}
internal abstract class BaseInvokableCall
{
protected BaseInvokableCall()
{}
protected BaseInvokableCall(object target, MethodInfo function)
{
if (function == null)
throw new ArgumentNullException(nameof(function));
if (function.IsStatic)
{
if (target != null)
throw new ArgumentException("target must be null");
}
else
{
if (target == null)
throw new ArgumentNullException("target");
}
}
public abstract void Invoke(object[] args);
protected static void ThrowOnInvalidArg<T>(object arg)
{
if (arg != null && !(arg is T))
throw new ArgumentException(UnityString.Format("Passed argument 'args[0]' is of the wrong type. Type:{0} Expected:{1}", arg.GetType(), typeof(T)));
}
protected static bool AllowInvoke(Delegate @delegate)
{
var target = @delegate.Target;
// static
if (target == null)
return true;
// UnityEngine object
var unityObj = target as Object;
if (!ReferenceEquals(unityObj, null))
return unityObj != null;
// Normal object
return true;
}
public abstract bool Find(object targetObj, MethodInfo method);
}
class InvokableCall : BaseInvokableCall
{
private event UnityAction Delegate;
public InvokableCall(object target, MethodInfo theFunction)
: base(target, theFunction)
{
Delegate += (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction);
}
public InvokableCall(UnityAction action)
{
Delegate += action;
}
public override void Invoke(object[] args)
{
if (AllowInvoke(Delegate))
Delegate();
}
public void Invoke()
{
if (AllowInvoke(Delegate))
Delegate();
}
public override bool Find(object targetObj, MethodInfo method)
{
// Case 827748: You can't compare Delegate.GetMethodInfo() == method, because sometimes it will not work, that's why we're using Equals instead, because it will compare that actual method inside.
// Comment from Microsoft:
// Desktop behavior regarding identity has never really been guaranteed. The desktop aggressively caches and reuses MethodInfo objects so identity checks often work by accident.
// .Net Native doesn’t guarantee identity and caches a lot less
return Delegate.Target == targetObj && Delegate.Method.Equals(method);
}
}
class InvokableCall<T1> : BaseInvokableCall
{
protected event UnityAction<T1> Delegate;
public InvokableCall(object target, MethodInfo theFunction)
: base(target, theFunction)
{
Delegate += (UnityAction<T1>)System.Delegate.CreateDelegate(typeof(UnityAction<T1>), target, theFunction);
}
public InvokableCall(UnityAction<T1> action)
{
Delegate += action;
}
public override void Invoke(object[] args)
{
if (args.Length != 1)
throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1");
ThrowOnInvalidArg<T1>(args[0]);
if (AllowInvoke(Delegate))
Delegate((T1)args[0]);
}
public virtual void Invoke(T1 args0)
{
if (AllowInvoke(Delegate))
Delegate(args0);
}
public override bool Find(object targetObj, MethodInfo method)
{
return Delegate.Target == targetObj && Delegate.Method.Equals(method);
}
}
class InvokableCall<T1, T2> : BaseInvokableCall
{
protected event UnityAction<T1, T2> Delegate;
public InvokableCall(object target, MethodInfo theFunction)
: base(target, theFunction)
{
Delegate = (UnityAction<T1, T2>)System.Delegate.CreateDelegate(typeof(UnityAction<T1, T2>), target, theFunction);
}
public InvokableCall(UnityAction<T1, T2> action)
{
Delegate += action;
}
public override void Invoke(object[] args)
{
if (args.Length != 2)
throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1");
ThrowOnInvalidArg<T1>(args[0]);
ThrowOnInvalidArg<T2>(args[1]);
if (AllowInvoke(Delegate))
Delegate((T1)args[0], (T2)args[1]);
}
public void Invoke(T1 args0, T2 args1)
{
if (AllowInvoke(Delegate))
Delegate(args0, args1);
}
public override bool Find(object targetObj, MethodInfo method)
{
return Delegate.Target == targetObj && Delegate.Method.Equals(method);
}
}
class InvokableCall<T1, T2, T3> : BaseInvokableCall
{
protected event UnityAction<T1, T2, T3> Delegate;
public InvokableCall(object target, MethodInfo theFunction)
: base(target, theFunction)
{
Delegate = (UnityAction<T1, T2, T3>)System.Delegate.CreateDelegate(typeof(UnityAction<T1, T2, T3>), target, theFunction);
}
public InvokableCall(UnityAction<T1, T2, T3> action)
{
Delegate += action;
}
public override void Invoke(object[] args)
{
if (args.Length != 3)
throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1");
ThrowOnInvalidArg<T1>(args[0]);
ThrowOnInvalidArg<T2>(args[1]);
ThrowOnInvalidArg<T3>(args[2]);
if (AllowInvoke(Delegate))
Delegate((T1)args[0], (T2)args[1], (T3)args[2]);
}
public void Invoke(T1 args0, T2 args1, T3 args2)
{
if (AllowInvoke(Delegate))
Delegate(args0, args1, args2);
}
public override bool Find(object targetObj, MethodInfo method)
{
return Delegate.Target == targetObj && Delegate.Method.Equals(method);
}
}
class InvokableCall<T1, T2, T3, T4> : BaseInvokableCall
{
protected event UnityAction<T1, T2, T3, T4> Delegate;
public InvokableCall(object target, MethodInfo theFunction)
: base(target, theFunction)
{
Delegate = (UnityAction<T1, T2, T3, T4>)System.Delegate.CreateDelegate(typeof(UnityAction<T1, T2, T3, T4>), target, theFunction);
}
public InvokableCall(UnityAction<T1, T2, T3, T4> action)
{
Delegate += action;
}
public override void Invoke(object[] args)
{
if (args.Length != 4)
throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1");
ThrowOnInvalidArg<T1>(args[0]);
ThrowOnInvalidArg<T2>(args[1]);
ThrowOnInvalidArg<T3>(args[2]);
ThrowOnInvalidArg<T4>(args[3]);
if (AllowInvoke(Delegate))
Delegate((T1)args[0], (T2)args[1], (T3)args[2], (T4)args[3]);
}
public void Invoke(T1 args0, T2 args1, T3 args2, T4 args3)
{
if (AllowInvoke(Delegate))
Delegate(args0, args1, args2, args3);
}
public override bool Find(object targetObj, MethodInfo method)
{
return Delegate.Target == targetObj && Delegate.Method.Equals(method);
}
}
class CachedInvokableCall<T> : InvokableCall<T>
{
private readonly T m_Arg1;
public CachedInvokableCall(Object target, MethodInfo theFunction, T argument)
: base(target, theFunction)
{
m_Arg1 = argument;
}
public override void Invoke(object[] args)
{
base.Invoke(m_Arg1);
}
public override void Invoke(T arg0)
{
base.Invoke(m_Arg1);
}
}
public enum UnityEventCallState
{
Off = 0,
EditorAndRuntime = 1,
RuntimeOnly = 2,
}
[Serializable]
class PersistentCall : ISerializationCallbackReceiver
{
//keep the layout of this class in sync with MonoPersistentCall in PersistentCallCollection.cpp
[FormerlySerializedAs("instance")]
[SerializeField]
private Object m_Target;
[SerializeField]
private string m_TargetAssemblyTypeName;
[FormerlySerializedAs("methodName")]
[SerializeField]
private string m_MethodName;
[FormerlySerializedAs("mode")]
[SerializeField]
private PersistentListenerMode m_Mode = PersistentListenerMode.EventDefined;
[FormerlySerializedAs("arguments")]
[SerializeField]
private ArgumentCache m_Arguments = new ArgumentCache();
[FormerlySerializedAs("enabled")]
[FormerlySerializedAs("m_Enabled")]
[SerializeField]
private UnityEventCallState m_CallState = UnityEventCallState.RuntimeOnly;
public Object target
{
get { return m_Target; }
}
public string targetAssemblyTypeName
{
get
{
// Reconstruct TargetAssemblyTypeName from target if it's not present, for ex., when upgrading project
if (string.IsNullOrEmpty(m_TargetAssemblyTypeName) && m_Target != null)
{
m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_Target.GetType().AssemblyQualifiedName);
}
return m_TargetAssemblyTypeName;
}
}
public string methodName
{
get { return m_MethodName; }
}
public PersistentListenerMode mode
{
get { return m_Mode; }
set { m_Mode = value; }
}
public ArgumentCache arguments
{
get { return m_Arguments; }
}
public UnityEventCallState callState
{
get { return m_CallState; }
set { m_CallState = value; }
}
public bool IsValid()
{
// We need to use the same logic found in PersistentCallCollection.cpp, IsPersistentCallValid
return !String.IsNullOrEmpty(targetAssemblyTypeName) && !String.IsNullOrEmpty(methodName);
}
public BaseInvokableCall GetRuntimeCall(UnityEventBase theEvent)
{
if (m_CallState == UnityEventCallState.RuntimeOnly && (target != null ? !Application.IsPlaying(target) : !Application.isPlaying))
return null;
if (m_CallState == UnityEventCallState.Off || theEvent == null)
return null;
var method = theEvent.FindMethod(this);
if (method == null)
return null;
if (!method.IsStatic && target == null)
return null;
var targetObject = method.IsStatic ? null : target;
switch (m_Mode)
{
case PersistentListenerMode.EventDefined:
return theEvent.GetDelegate(targetObject, method);
case PersistentListenerMode.Object:
return GetObjectCall(targetObject, method, m_Arguments);
case PersistentListenerMode.Float:
return new CachedInvokableCall<float>(targetObject, method, m_Arguments.floatArgument);
case PersistentListenerMode.Int:
return new CachedInvokableCall<int>(targetObject, method, m_Arguments.intArgument);
case PersistentListenerMode.String:
return new CachedInvokableCall<string>(targetObject, method, m_Arguments.stringArgument);
case PersistentListenerMode.Bool:
return new CachedInvokableCall<bool>(targetObject, method, m_Arguments.boolArgument);
case PersistentListenerMode.Void:
return new InvokableCall(targetObject, method);
}
return null;
}
// need to generate a generic typed version of the call here
// this is due to the fact that we allow binding of 'any'
// functions that extend object.
private static BaseInvokableCall GetObjectCall(Object target, MethodInfo method, ArgumentCache arguments)
{
var type = typeof(Object);
if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName))
type = Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, false) ?? typeof(Object);
var generic = typeof(CachedInvokableCall<>);
var specific = generic.MakeGenericType(type);
var ci = specific.GetConstructor(new[] { typeof(Object), typeof(MethodInfo), type});
var castedObject = arguments.unityObjectArgument;
if (castedObject != null && !type.IsAssignableFrom(castedObject.GetType()))
castedObject = null;
// need to pass explicit null here!
return ci.Invoke(new object[] {target, method, castedObject}) as BaseInvokableCall;
}
public void RegisterPersistentListener(Object ttarget, Type targetType, string mmethodName)
{
m_Target = ttarget;
m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(targetType.AssemblyQualifiedName);
m_MethodName = mmethodName;
}
public void UnregisterPersistentListener()
{
m_MethodName = string.Empty;
m_Target = null;
m_TargetAssemblyTypeName = string.Empty;
}
public void OnBeforeSerialize()
{
m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_TargetAssemblyTypeName);
}
public void OnAfterDeserialize()
{
m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_TargetAssemblyTypeName);
}
}
[Serializable]
internal class PersistentCallGroup
{
[FormerlySerializedAs("m_Listeners")]
[SerializeField] private List<PersistentCall> m_Calls;
public PersistentCallGroup()
{
m_Calls = new List<PersistentCall>();
}
public int Count
{
get { return m_Calls.Count; }
}
public PersistentCall GetListener(int index)
{
return m_Calls[index];
}
public IEnumerable<PersistentCall> GetListeners()
{
return m_Calls;
}
public void AddListener()
{
m_Calls.Add(new PersistentCall());
}
public void AddListener(PersistentCall call)
{
m_Calls.Add(call);
}
public void RemoveListener(int index)
{
m_Calls.RemoveAt(index);
}
public void Clear()
{
m_Calls.Clear();
}
public void RegisterEventPersistentListener(int index, Object targetObj, Type targetObjType, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.EventDefined;
}
public void RegisterVoidPersistentListener(int index, Object targetObj, Type targetObjType, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.Void;
}
public void RegisterObjectPersistentListener(int index, Object targetObj, Type targetObjType, Object argument, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.Object;
listener.arguments.unityObjectArgument = argument;
}
public void RegisterIntPersistentListener(int index, Object targetObj, Type targetObjType, int argument, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.Int;
listener.arguments.intArgument = argument;
}
public void RegisterFloatPersistentListener(int index, Object targetObj, Type targetObjType, float argument, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.Float;
listener.arguments.floatArgument = argument;
}
public void RegisterStringPersistentListener(int index, Object targetObj, Type targetObjType, string argument, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.String;
listener.arguments.stringArgument = argument;
}
public void RegisterBoolPersistentListener(int index, Object targetObj, Type targetObjType, bool argument, string methodName)
{
var listener = GetListener(index);
listener.RegisterPersistentListener(targetObj, targetObjType, methodName);
listener.mode = PersistentListenerMode.Bool;
listener.arguments.boolArgument = argument;
}
public void UnregisterPersistentListener(int index)
{
var evt = GetListener(index);
evt.UnregisterPersistentListener();
}
public void RemoveListeners(Object target, string methodName)
{
var toRemove = new List<PersistentCall>();
for (int index = 0; index < m_Calls.Count; index++)
{
if (m_Calls[index].target == target && m_Calls[index].methodName == methodName)
toRemove.Add(m_Calls[index]);
}
m_Calls.RemoveAll(toRemove.Contains);
}
public void Initialize(InvokableCallList invokableList, UnityEventBase unityEventBase)
{
foreach (var persistentCall in m_Calls)
{
if (!persistentCall.IsValid())
continue;
var call = persistentCall.GetRuntimeCall(unityEventBase);
if (call != null)
invokableList.AddPersistentInvokableCall(call);
}
}
}
class InvokableCallList
{
private readonly List<BaseInvokableCall> m_PersistentCalls = new List<BaseInvokableCall>();
private readonly List<BaseInvokableCall> m_RuntimeCalls = new List<BaseInvokableCall>();
private List<BaseInvokableCall> m_ExecutingCalls = new List<BaseInvokableCall>();
private bool m_NeedsUpdate = true;
public int Count
{
get { return m_PersistentCalls.Count + m_RuntimeCalls.Count; }
}
public void AddPersistentInvokableCall(BaseInvokableCall call)
{
m_PersistentCalls.Add(call);
m_NeedsUpdate = true;
}
public void AddListener(BaseInvokableCall call)
{
m_RuntimeCalls.Add(call);
m_NeedsUpdate = true;
}
public void RemoveListener(object targetObj, MethodInfo method)
{
var toRemove = new List<BaseInvokableCall>();
for (int index = 0; index < m_RuntimeCalls.Count; index++)
{
if (m_RuntimeCalls[index].Find(targetObj, method))
toRemove.Add(m_RuntimeCalls[index]);
}
m_RuntimeCalls.RemoveAll(toRemove.Contains);
// removals are done synchronously to avoid leaks
var newExecutingCalls = new List<BaseInvokableCall>(m_PersistentCalls.Count + m_RuntimeCalls.Count);
newExecutingCalls.AddRange(m_PersistentCalls);
newExecutingCalls.AddRange(m_RuntimeCalls);
m_ExecutingCalls = newExecutingCalls;
m_NeedsUpdate = false;
}
public void Clear()
{
m_RuntimeCalls.Clear();
// removals are done synchronously to avoid leaks
var newExecutingCalls = new List<BaseInvokableCall>(m_PersistentCalls);
m_ExecutingCalls = newExecutingCalls;
m_NeedsUpdate = false;
}
public void ClearPersistent()
{
m_PersistentCalls.Clear();
// removals are done synchronously to avoid leaks
var newExecutingCalls = new List<BaseInvokableCall>(m_RuntimeCalls);
m_ExecutingCalls = newExecutingCalls;
m_NeedsUpdate = false;
}
public List<BaseInvokableCall> PrepareInvoke()
{
if (m_NeedsUpdate)
{
m_ExecutingCalls.Clear();
m_ExecutingCalls.AddRange(m_PersistentCalls);
m_ExecutingCalls.AddRange(m_RuntimeCalls);
m_NeedsUpdate = false;
}
return m_ExecutingCalls;
}
}
[Serializable]
[UsedByNativeCode]
public abstract class UnityEventBase : ISerializationCallbackReceiver
{
private InvokableCallList m_Calls;
[FormerlySerializedAs("m_PersistentListeners")]
[SerializeField]
private PersistentCallGroup m_PersistentCalls;
// Dirtying can happen outside of MainThread, but we need to rebuild on the MainThread.
private bool m_CallsDirty = true;
protected UnityEventBase()
{
m_Calls = new InvokableCallList();
m_PersistentCalls = new PersistentCallGroup();
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
DirtyPersistentCalls();
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
DirtyPersistentCalls();
}
protected MethodInfo FindMethod_Impl(string name, object targetObj)
{
return FindMethod_Impl(name, targetObj.GetType());
}
protected abstract MethodInfo FindMethod_Impl(string name, Type targetObjType);
internal abstract BaseInvokableCall GetDelegate(object target, MethodInfo theFunction);
internal MethodInfo FindMethod(PersistentCall call)
{
var type = typeof(Object);
if (!string.IsNullOrEmpty(call.arguments.unityObjectArgumentAssemblyTypeName))
type = Type.GetType(call.arguments.unityObjectArgumentAssemblyTypeName, false) ?? typeof(Object);
var targetType = call.target != null ? call.target.GetType() : Type.GetType(call.targetAssemblyTypeName, false);
return FindMethod(call.methodName, targetType, call.mode, type);
}
internal MethodInfo FindMethod(string name, Type listenerType, PersistentListenerMode mode, Type argumentType)
{
switch (mode)
{
case PersistentListenerMode.EventDefined:
return FindMethod_Impl(name, listenerType);
case PersistentListenerMode.Void:
return GetValidMethodInfo(listenerType, name, new Type[0]);
case PersistentListenerMode.Float:
return GetValidMethodInfo(listenerType, name, new[] { typeof(float) });
case PersistentListenerMode.Int:
return GetValidMethodInfo(listenerType, name, new[] { typeof(int) });
case PersistentListenerMode.Bool:
return GetValidMethodInfo(listenerType, name, new[] { typeof(bool) });
case PersistentListenerMode.String:
return GetValidMethodInfo(listenerType, name, new[] { typeof(string) });
case PersistentListenerMode.Object:
return GetValidMethodInfo(listenerType, name, new[] { argumentType ?? typeof(Object) });
default:
return null;
}
}
public int GetPersistentEventCount()
{
return m_PersistentCalls.Count;
}
public Object GetPersistentTarget(int index)
{
var listener = m_PersistentCalls.GetListener(index);
return listener != null ? listener.target : null;
}
public string GetPersistentMethodName(int index)
{
var listener = m_PersistentCalls.GetListener(index);
return listener != null ? listener.methodName : string.Empty;
}
private void DirtyPersistentCalls()
{
m_Calls.ClearPersistent();
m_CallsDirty = true;
}
// Can only run on MainThread
private void RebuildPersistentCallsIfNeeded()
{
if (m_CallsDirty)
{
m_PersistentCalls.Initialize(m_Calls, this);
m_CallsDirty = false;
}
}
public void SetPersistentListenerState(int index, UnityEventCallState state)
{
var listener = m_PersistentCalls.GetListener(index);
if (listener != null)
listener.callState = state;
DirtyPersistentCalls();
}
public UnityEventCallState GetPersistentListenerState(int index)
{
if (index < 0 || index > m_PersistentCalls.Count)
throw new IndexOutOfRangeException($"Index {index} is out of range of the {GetPersistentEventCount()} persistent listeners.");
return m_PersistentCalls.GetListener(index).callState;
}
protected void AddListener(object targetObj, MethodInfo method)
{
m_Calls.AddListener(GetDelegate(targetObj, method));
}
internal void AddCall(BaseInvokableCall call)
{
m_Calls.AddListener(call);
}
protected void RemoveListener(object targetObj, MethodInfo method)
{
m_Calls.RemoveListener(targetObj, method);
}
public void RemoveAllListeners()
{
m_Calls.Clear();
}
internal List<BaseInvokableCall> PrepareInvoke()
{
RebuildPersistentCallsIfNeeded();
return m_Calls.PrepareInvoke();
}
protected void Invoke(object[] parameters)
{
List<BaseInvokableCall> calls = PrepareInvoke();
for (var i = 0; i < calls.Count; i++)
calls[i].Invoke(parameters);
}
public override string ToString()
{
return base.ToString() + " " + GetType().FullName;
}
// Find a valid method that can be bound to an event with a given name
public static MethodInfo GetValidMethodInfo(object obj, string functionName, Type[] argumentTypes)
{
return GetValidMethodInfo(obj.GetType(), functionName, argumentTypes);
}
public static MethodInfo GetValidMethodInfo(Type objectType, string functionName, Type[] argumentTypes)
{
while (objectType != typeof(object) && objectType != null)
{
var method = objectType.GetMethod(functionName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, argumentTypes, null);
if (method != null)
{
// We need to make sure the Arguments are sane. When using the Type.DefaultBinder like we are above,
// it is possible to receive a method that takes a System.Object enve though we requested a float, int or bool.
// This can be an issue when the user changes the signature of a function that he had already set up via inspector.
// When changing a float parameter to a System.Object the getMethod would still bind to the cahnged version, but
// the PersistentListenerMode would still be kept as Float.
// TODO: Should we allow anything else besides Primitive types and types derived from UnityEngine.Object?
var parameterInfos = method.GetParameters();
var methodValid = true;
var i = 0;
foreach (ParameterInfo pi in parameterInfos)
{
var requestedType = argumentTypes[i];
var receivedType = pi.ParameterType;
methodValid = requestedType.IsPrimitive == receivedType.IsPrimitive;
if (!methodValid)
break;
i++;
}
if (methodValid)
return method;
}
objectType = objectType.BaseType;
}
return null;
}
protected bool ValidateRegistration(MethodInfo method, object targetObj, PersistentListenerMode mode)
{
return ValidateRegistration(method, targetObj, mode, typeof(Object));
}
protected bool ValidateRegistration(MethodInfo method, object targetObj, PersistentListenerMode mode, Type argumentType)
{
if (method == null)
throw new ArgumentNullException("method", UnityString.Format("Can not register null method on {0} for callback!", targetObj));
if (method.DeclaringType == null)
{
throw new NullReferenceException(
UnityString.Format(
"Method '{0}' declaring type is null, global methods are not supported",
method.Name));
}
Type targetType;
if (!method.IsStatic)
{
var obj = targetObj as Object;
if (obj == null || obj.GetInstanceID() == 0)
{
throw new ArgumentException(
UnityString.Format(
"Could not register callback {0} on {1}. The class {2} does not derive from UnityEngine.Object",
method.Name,
targetObj,
targetObj == null ? "null" : targetObj.GetType().ToString()));
}
targetType = obj.GetType();
if (!method.DeclaringType.IsAssignableFrom(targetType))
throw new ArgumentException(
UnityString.Format(
"Method '{0}' declaring type '{1}' is not assignable from object type '{2}'",
method.Name,
method.DeclaringType.Name,
obj.GetType().Name));
}
else
{
targetType = method.DeclaringType;
}
if (FindMethod(method.Name, targetType, mode, argumentType) == null)
{
Debug.LogWarning(UnityString.Format("Could not register listener {0}.{1} on {2} the method could not be found.", targetObj, method, GetType()));
return false;
}
return true;
}
internal void AddPersistentListener()
{
m_PersistentCalls.AddListener();
}
protected void RegisterPersistentListener(int index, object targetObj, MethodInfo method)
{
RegisterPersistentListener(index, targetObj, targetObj.GetType(), method);