Created
February 19, 2023 20:25
-
-
Save ricardj/1d1b6997244c13dfaf0b1698cd15d6f5 to your computer and use it in GitHub Desktop.
Unity Event Bus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System; | |
public class EventBus | |
{ | |
private static EventBus instance = null; | |
public static EventBus Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
instance = new EventBus(); | |
} | |
return instance; | |
} | |
} | |
private Dictionary<Type, Delegate> eventDictionary; | |
private EventBus() | |
{ | |
eventDictionary = new Dictionary<Type, Delegate>(); | |
} | |
public void AddListener<T>(Action<T> listener) where T : class | |
{ | |
if (eventDictionary.ContainsKey(typeof(T))) | |
{ | |
eventDictionary[typeof(T)] = Delegate.Combine(eventDictionary[typeof(T)], listener); | |
} | |
else | |
{ | |
eventDictionary.Add(typeof(T), listener); | |
} | |
} | |
public void RemoveListener<T>(Action<T> listener) where T : class | |
{ | |
if (eventDictionary.ContainsKey(typeof(T))) | |
{ | |
eventDictionary[typeof(T)] = Delegate.Remove(eventDictionary[typeof(T)], listener); | |
} | |
} | |
public void TriggerEvent<T>(T eventObject) where T : class | |
{ | |
if (eventDictionary.TryGetValue(typeof(T), out Delegate listener)) | |
{ | |
((Action<T>)listener)?.Invoke(eventObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment