Created
April 25, 2020 21:32
-
-
Save CRodriguez25/1ddafe2dbd889b636b10d2196554b6eb to your computer and use it in GitHub Desktop.
Unity Game Event Message 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; | |
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