Skip to content

Instantly share code, notes, and snippets.

@darktable
Created April 11, 2023 15:04
Show Gist options
  • Select an option

  • Save darktable/b439f0637f6331ee6fe0419a8a3fd7e2 to your computer and use it in GitHub Desktop.

Select an option

Save darktable/b439f0637f6331ee6fe0419a8a3fd7e2 to your computer and use it in GitHub Desktop.

Revisions

  1. darktable created this gist Apr 11, 2023.
    78 changes: 78 additions & 0 deletions EventManager.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    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();
    }
    }
    }