A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3using UnityEngine;
4
5namespace Unity.VisualScripting
6{
7 public static class EventBus
8 {
9 static EventBus()
10 {
11 events = new Dictionary<EventHook, HashSet<Delegate>>(new EventHookComparer());
12 }
13
14 private static readonly Dictionary<EventHook, HashSet<Delegate>> events;
15 internal static Dictionary<EventHook, HashSet<Delegate>> testAccessEvents => events;
16
17 public static void Register<TArgs>(EventHook hook, Action<TArgs> handler)
18 {
19 if (!events.TryGetValue(hook, out var handlers))
20 {
21 handlers = new HashSet<Delegate>();
22 events.Add(hook, handlers);
23 }
24
25 handlers.Add(handler);
26 }
27
28 public static void Unregister(EventHook hook, Delegate handler)
29 {
30 if (events.TryGetValue(hook, out var handlers))
31 {
32 if (handlers.Remove(handler))
33 {
34 // Free the key references for GC collection
35 if (handlers.Count == 0)
36 {
37 events.Remove(hook);
38 }
39 }
40 }
41 }
42
43 public static void Trigger<TArgs>(EventHook hook, TArgs args)
44 {
45 HashSet<Action<TArgs>> handlers = null;
46
47 if (events.TryGetValue(hook, out var potentialHandlers))
48 {
49 foreach (var potentialHandler in potentialHandlers)
50 {
51 if (potentialHandler is Action<TArgs> handler)
52 {
53 if (handlers == null)
54 {
55 handlers = HashSetPool<Action<TArgs>>.New();
56 }
57
58 handlers.Add(handler);
59 }
60 }
61 }
62
63 if (handlers != null)
64 {
65 foreach (var handler in handlers)
66 {
67 if (!potentialHandlers.Contains(handler))
68 {
69 continue;
70 }
71
72 handler.Invoke(args);
73 }
74
75 handlers.Free();
76 }
77 }
78
79 public static void Trigger<TArgs>(string name, GameObject target, TArgs args)
80 {
81 Trigger(new EventHook(name, target), args);
82 }
83
84 public static void Trigger(EventHook hook)
85 {
86 Trigger(hook, new EmptyEventArgs());
87 }
88
89 public static void Trigger(string name, GameObject target)
90 {
91 Trigger(new EventHook(name, target));
92 }
93 }
94}