-
Notifications
You must be signed in to change notification settings - Fork 0
/
CategorizedEnumEvents.cs
81 lines (73 loc) · 2.66 KB
/
CategorizedEnumEvents.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
#if UNITY_EDITOR
using System;
using UnityEditor;
namespace CategorizedEnum {
public delegate void OnSelectEventEvent();
/// <summary>
/// This events class is used to listen to categorized enum specific events from everywhere
/// </summary>
public class Events {
/// On Select event. This is useful for editor scripting if something should update right after a enum value was changed
public event OnSelectEventEvent onSelect;
private static Events instance;
/// <summary>
/// Get the current instance of this class. Beware, this is an "Evil" Singleton.
/// It makes sense in this case, since categorized enums don't have a central structure so having a globally referencable event class to listen to the events from anywhere is very handy.
/// </summary>
public static Events Instance {
get {
if (instance == null) {
Initialize();
}
return instance;
}
}
/// <summary>
/// Initialize method, this should initialize when the editor is opened & right after compilation
/// </summary>
[InitializeOnLoadMethod]
public static void Initialize() {
instance = new Events();
Dispose();
EditorApplication.wantsToQuit -= WantsToQuit;
EditorApplication.wantsToQuit += WantsToQuit;
}
/// <summary>
/// Dispose all listeners right before the editor quits
/// </summary>
/// <returns></returns>
private static bool WantsToQuit() {
Dispose();
return true;
}
/// <summary>
/// add another on select event listener
/// </summary>
/// <param name="listener"></param>
/// <param name="removePrevious"></param>
public static void AddOnSelectListener(OnSelectEventEvent listener, bool removePrevious = true) {
if (removePrevious) {
instance.onSelect -= listener;
}
instance.onSelect += listener;
}
/// <summary>
/// fire the OnSelect event
/// </summary>
public static void FireOnSelect() {
instance.onSelect?.Invoke();
}
/// <summary>
/// Dispose all events
/// </summary>
public static void Dispose() {
// Purge OnBackendReadyEvents
if (instance.onSelect != null) {
foreach (Delegate d in instance.onSelect.GetInvocationList()) {
instance.onSelect -= (OnSelectEventEvent)d;
}
}
}
}
}
#endif