Skip to content

Instantly share code, notes, and snippets.

@darktable
Created April 11, 2023 15:04
Show Gist options
  • Save darktable/b439f0637f6331ee6fe0419a8a3fd7e2 to your computer and use it in GitHub Desktop.
Save darktable/b439f0637f6331ee6fe0419a8a3fd7e2 to your computer and use it in GitHub Desktop.
EventManager script found in the Unity's FPS Micro Game sample. Useful for global event broadcasting.
using System;
using System.Collections.Generic;
namespace Unity.FPS.Game
{
public interface IBroadcastEvent { }
// A simple Event System that can be used for remote systems communication
public static class EventManager
{
private static readonly Dictionary<Type, Action<IBroadcastEvent>> k_Events =
new Dictionary<Type, Action<IBroadcastEvent>>();
private static readonly Dictionary<Delegate, Action<IBroadcastEvent>> k_EventLookups =
new Dictionary<Delegate, Action<IBroadcastEvent>>();
public static void AddListener<T>(Action<T> evt) where T : class, IBroadcastEvent
{
if (!k_EventLookups.ContainsKey(evt))
{
return;
}
Action<IBroadcastEvent> newAction = (e) => evt((T)e);
k_EventLookups[evt] = newAction;
var type = typeof(T);
if (k_Events.TryGetValue(type, out Action<IBroadcastEvent> internalAction))
{
k_Events[type] = internalAction += newAction;
}
else
{
k_Events[type] = newAction;
}
}
public static void RemoveListener<T>(Action<T> evt) where T : class, IBroadcastEvent
{
if (!k_EventLookups.TryGetValue(evt, out var action))
{
return;
}
var type = typeof(T);
if (k_Events.TryGetValue(type, out var tempAction))
{
tempAction -= action;
if (tempAction == null)
{
k_Events.Remove(type);
}
else
{
k_Events[type] = tempAction;
}
}
k_EventLookups.Remove(evt);
}
public static void Broadcast<T>(T evt) where T : class, IBroadcastEvent
{
if (k_Events.TryGetValue(evt.GetType(), out var action))
{
action.Invoke(evt);
}
}
public static void Clear()
{
k_Events.Clear();
k_EventLookups.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment