-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathEventSystem.cs
More file actions
78 lines (65 loc) · 2.26 KB
/
EventSystem.cs
File metadata and controls
78 lines (65 loc) · 2.26 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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace EventCallbacks
{
public class EventSystem
{
private static Dictionary<Type, EventSystem> _systems = new Dictionary<Type, EventSystem>();
public static void Register<T>(Action<T> listener) where T : EventInfo
{
Type eventType = typeof(T);
if (_systems == null)
{
_systems = new Dictionary<Type, EventSystem>();
}
if (!_systems.ContainsKey(eventType) || _systems[eventType] == null)
{
_systems[eventType] = new EventSystem<T>();
}
((EventSystem<T>)_systems[eventType]).RegisterListener(listener);
}
public static void FireEvent<T>(T eventInfo) where T : EventInfo
{
Type eventType = typeof(T);
if (_systems?[eventType] == null)
{
// No one is listening, we are done.
return;
}
((EventSystem<T>)_systems[eventType]).FireEvent(eventInfo);
}
}
public class EventSystem<T> : EventSystem where T : EventInfo
{
private Dictionary<Type, Action<T>> _eventListeners;
public void RegisterListener(Action<T> listener)
{
// Can't ever be null as it's initialised with class
if (_eventListeners == null)
{
_eventListeners = new Dictionary<Type, Action<T>>();
}
Type eventType = typeof(T);
if (!_eventListeners.ContainsKey(eventType))
_eventListeners[eventType] = listener;
else
_eventListeners[eventType] += listener;
}
public void UnregisterListener(Action<T> listener)
{
// TODO
}
public void FireEvent(T eventInfo)
{
Type trueEventInfoClass = typeof(T);
if (_eventListeners?[trueEventInfoClass] == null)
{
// No one is listening, we are done.
return;
}
_eventListeners[trueEventInfoClass]?.Invoke(eventInfo);
}
}
}