Skip to content

Instantly share code, notes, and snippets.

@CRodriguez25
Created April 25, 2020 21:32
Show Gist options
  • Save CRodriguez25/1ddafe2dbd889b636b10d2196554b6eb to your computer and use it in GitHub Desktop.
Save CRodriguez25/1ddafe2dbd889b636b10d2196554b6eb to your computer and use it in GitHub Desktop.
Unity Game Event Message Bus
using System;
using System.Collections.Generic;
public class GameEventMessageBus
{
private static Dictionary<Type, List<Action<object>>> _subscriberDict = new Dictionary<Type, List<Action<object>>>();
public static void Subscribe<T>(Action<T> handler)
{
var type = typeof(T);
InitializeTypeKey(type);
_subscriberDict[type].Add(new Action<object>(o => handler((T)o)));
}
private static void InitializeTypeKey(Type key)
{
if (!_subscriberDict.ContainsKey(key))
_subscriberDict.Add(key, new List<Action<object>>());
}
public static void Emit<T>(T message)
{
var type = typeof(T);
InitializeTypeKey(type);
foreach(var handler in _subscriberDict[type])
handler.Invoke(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment