Skip to content

Instantly share code, notes, and snippets.

@ricardj
Created February 19, 2023 20:25
Show Gist options
  • Save ricardj/1d1b6997244c13dfaf0b1698cd15d6f5 to your computer and use it in GitHub Desktop.
Save ricardj/1d1b6997244c13dfaf0b1698cd15d6f5 to your computer and use it in GitHub Desktop.
Unity Event Bus
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