-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathEventSystem.cs
More file actions
112 lines (96 loc) · 3.12 KB
/
EventSystem.cs
File metadata and controls
112 lines (96 loc) · 3.12 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
using System;
using System.Collections.Generic;
namespace EventCallbacks
{
public abstract class EventSystem
{
public abstract void CleanEventSystem();
}
/// <summary>
/// The actual generic eventsystem
/// </summary>
/// <typeparam name="T">The type of the event for this system</typeparam>
public class EventSystem<T> : EventSystem
{
static EventSystem<T> eventSystemInstance;
Action<T> eventDelegate;
public static event Action<T> EventTriggered
{
add
{
if (EventSystemInstance.eventDelegate == null)
{
EventSystemManagement.RegisterNewEventSystem(EventSystemInstance);
}
EventSystemInstance.eventDelegate += value;
}
remove { EventSystemInstance.eventDelegate -= value; }
}
public static void FireEvent(T eventData)
{
EventSystemInstance.FireEvent_(eventData);
}
static void CleanCurrentEventSystem()
{
if (eventSystemInstance != null)
{
eventSystemInstance.CleanSubscribersList();
// we set our instance to null, so we can check whether we have to create a new instance next time
eventSystemInstance = null;
}
}
static EventSystem<T> EventSystemInstance
{
get { return eventSystemInstance ?? (eventSystemInstance = new EventSystem<T>()); }
}
public override void CleanEventSystem()
{
// notice that we call a static method here
CleanCurrentEventSystem();
}
void CleanSubscribersList()
{
eventDelegate = null;
}
void FireEvent_(T eventData)
{
if (eventDelegate != null)
{
eventDelegate(eventData);
}
}
EventSystem()
{
}
}
/// <summary>
/// a management class used to cleanup every used event system
/// </summary>
public static class EventSystemManagement
{
static readonly List<EventSystem> eventSystems = new List<EventSystem>();
/// <summary>
/// Registers a new event system instance
/// </summary>
/// <param name="eventSystem">The event system instance to register</param>
public static void RegisterNewEventSystem(EventSystem eventSystem)
{
if (!eventSystems.Contains(eventSystem))
{
eventSystems.Add(eventSystem);
}
}
/// <summary>
/// removes the listeners of all registered event system instances and
/// clears the list of registered event systems
/// </summary>
public static void CleanupEventSystem()
{
foreach (var eventSystem in eventSystems)
{
eventSystem.CleanEventSystem();
}
eventSystems.Clear();
}
}
}