-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEventBus.cs
More file actions
256 lines (214 loc) · 7.44 KB
/
EventBus.cs
File metadata and controls
256 lines (214 loc) · 7.44 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
namespace EventBus
{
using System;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using EventBus.Internal;
using System.Collections;
using UnityEngine.Pool;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// Marks an assembly containing EventBus types.
/// Used to identify relevant assemblies for the EventBus system cleanup steps.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
public class EventBusAssemblyAttribute : Attribute
{
}
public static class EventBusUtility
{
public static IReadOnlyList<Type> EventTypes { get; private set; }
public static IReadOnlyList<Type> StaticEventBusesTypes { get; private set; }
#if UNITY_EDITOR
public static PlayModeStateChange PlayModeState { get; private set; }
[InitializeOnLoadMethod]
public static void InitializeEditor()
{
EditorApplication.playModeStateChanged -= HandleEditorStateChange;
EditorApplication.playModeStateChanged += HandleEditorStateChange;
}
private static void HandleEditorStateChange(PlayModeStateChange state)
{
PlayModeState = state;
if (PlayModeState == PlayModeStateChange.EnteredEditMode)
ClearAllBuses();
}
#endif
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Init()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Type[]> assemblyTypesToScan = ListPool<Type[]>.Get();
for (int i = 0; i < assemblies.Length; i++)
{
if (assemblies[i].GetName().Name == "Assembly-CSharp"
|| assemblies[i].GetName().Name == "Assembly-CSharp-firstpass"
|| assemblies[i].GetCustomAttribute<EventBusAssemblyAttribute>() is not null)
assemblyTypesToScan.Add(assemblies[i].GetTypes());
}
List<Type> eventTypes = new List<Type>();
foreach (var assemblyTypes in assemblyTypesToScan)
{
for (int i = 0; i < assemblyTypes.Length; i++)
{
var type = assemblyTypes[i];
if ((typeof(IEvent)) != type && (typeof(IEvent)).IsAssignableFrom(type))
{
eventTypes.Add(type);
}
}
}
ListPool<Type[]>.Release(assemblyTypesToScan);
EventTypes = eventTypes;
List<Type> staticEventBusesTypes = new List<Type>();
var typedef = typeof(EventBus<>);
for (int i = 0; i < EventTypes.Count; i++)
{
var type = EventTypes[i];
var gentype = typedef.MakeGenericType(type);
staticEventBusesTypes.Add(gentype);
}
StaticEventBusesTypes = staticEventBusesTypes;
}
public static void ClearAllBuses()
{
for (int i = 0; i < StaticEventBusesTypes.Count; i++)
{
var type = StaticEventBusesTypes[i];
var clearMethod = type.GetMethod("Clear", BindingFlags.Static | BindingFlags.NonPublic);
clearMethod.Invoke(null, null);
}
}
}
public static class EventBus<T> where T : struct, IEvent
{
private static EventBinding<T>[] bindings = new EventBinding<T>[64];
private static List<Callback> callbacks = new List<Callback>();
private static int count;
public class Awaiter : EventBinding<T>
{
public bool EventRaised { get; private set; }
public T Payload { get; private set; }
public Awaiter() : base((Action)null)
{
((IEventBindingInternal<T>)this).OnEvent = OnEvent;
}
private void OnEvent(T ev)
{
EventRaised = true;
Payload = ev;
}
}
private struct Callback
{
public Action onEventNoArg;
public Action<T> onEvent;
}
private static void Clear()
{
bindings = new EventBinding<T>[64];
callbacks.Clear();
count = 0;
}
public static void Register(EventBinding<T> binding)
{
if (binding.Registered)
return;
if (bindings.Length <= count)
{
EventBinding<T>[] newarray = new EventBinding<T>[bindings.Length * 2];
Array.Copy(bindings, newarray, bindings.Length);
bindings = newarray;
}
binding.InternalIndex = count;
bindings[count] = binding;
count++;
}
public static void AddCallback(Action callback)
{
if (callback == null)
return;
callbacks.Add(new Callback() { onEventNoArg = callback });
}
public static void AddCallback(Action<T> callback)
{
if (callback == null)
return;
callbacks.Add(new Callback() { onEvent = callback });
}
public static void Unregister(EventBinding<T> binding)
{
#if UNITY_EDITOR
if (EventBusUtility.PlayModeState == PlayModeStateChange.ExitingPlayMode)
return;
#endif
int index = binding.InternalIndex;
if (index == -1 || index > count)
{
// binding invalid
return;
}
if (bindings[index] != binding)
{
// binding invalid
return;
}
if (index == count - 1)
{
bindings[count - 1] = null;
binding.InternalIndex = -1;
count--;
return;
}
int lastIndex = count - 1;
var last = bindings[lastIndex];
bindings[index] = last;
bindings[lastIndex] = null;
if (last != null)
last.InternalIndex = index;
binding.InternalIndex = -1;
count--;
}
public static void Raise()
{
Raise(default);
}
public static void Raise(T ev)
{
#if UNITY_EDITOR
if (EventBusUtility.PlayModeState == PlayModeStateChange.ExitingPlayMode)
return;
#endif
for (int i = 0; i < count; i++)
{
IEventBindingInternal<T> internalBind = bindings[i];
internalBind.OnEvent?.Invoke(ev);
internalBind.OnEventArgs?.Invoke();
}
for (int i = 0; i < callbacks.Count; i++)
{
callbacks[i].onEvent?.Invoke(ev);
callbacks[i].onEventNoArg?.Invoke();
}
callbacks.Clear();
}
public static string GetDebugInfoString()
{
return "Bindings: " + count + " BufferSize: " + bindings.Length + "\n"
+ "Callbacks: " + callbacks.Count;
}
/// <summary>
/// Allocates an Awaiter : EventBinding<T>
/// Use to await event in coroutines
/// </summary>
/// <returns></returns>
public static Awaiter NewAwaiter()
{
// TODO: do it non alloc
return new Awaiter();
}
}
}