Skip to content

Instantly share code, notes, and snippets.

@vncastanheira
Created March 14, 2023 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vncastanheira/6883e79d10c7dc405e0240fe11e27bf7 to your computer and use it in GitHub Desktop.
Save vncastanheira/6883e79d10c7dc405e0240fe11e27bf7 to your computer and use it in GitHub Desktop.
Global event system for Unity
using System;
using System.Collections.Generic;
using UnityEngine;
namespace vnc.Tools
{
/// <summary> Global event system </summary>
public static class VncEventSystem
{
static Dictionary<Type, List<IVncEventListenerGeneric>> _events;
static VncEventSystem()
{
_events = new Dictionary<Type, List<IVncEventListenerGeneric>>();
}
/// <summary>
/// Start listening to events
/// </summary>
/// <typeparam name="VncEvent">Type of event to listen to</typeparam>
/// <param name="listener">Register itself as event listener</param>
public static void Listen<VncEvent>(this IVncEventListener<VncEvent> listener) where VncEvent : struct
{
Type eType = typeof(VncEvent);
List<IVncEventListenerGeneric> _eventList;
if (!_events.ContainsKey(eType))
{
_eventList = new List<IVncEventListenerGeneric>();
_events.Add(eType, _eventList);
}
else
{
_eventList = _events[eType];
}
if (!_eventList.Contains(listener))
_eventList.Add(listener);
}
/// <summary>
/// Stop listening to events
/// </summary>
/// <typeparam name="VncEvent">Type of event to unlisten to</typeparam>
/// <param name="listener">Remove itself as event listener</param>
public static void Unlisten<VncEvent>(this IVncEventListener<VncEvent> listener) where VncEvent : struct
{
List<IVncEventListenerGeneric> _eventList;
if (_events.TryGetValue(typeof(VncEvent), out _eventList))
{
_eventList.Remove(listener);
}
else
{
throw new UnityException("Cannot unlisten this listener. It doesn't exist.");
}
}
/// <summary>
/// Trigger an event
/// </summary>
/// <typeparam name="VncEvent">A generic struct</typeparam>
/// <param name="vncEvent">Event message to send to all lintener</param>
public static void Trigger<VncEvent>(VncEvent vncEvent) where VncEvent : struct
{
List<IVncEventListenerGeneric> _eventList;
if (!_events.TryGetValue(typeof(VncEvent), out _eventList))
Debug.LogWarningFormat("'{0}' doesn't exist. Make sure to listen to it first.", typeof(VncEvent).Name);
else
{
foreach (IVncEventListener<VncEvent> e in _eventList)
e.OnVncEvent(vncEvent);
}
}
}
public interface IVncEventListenerGeneric { }
/// <summary>
/// Inherit this interface to start listening to events.
/// Don't forget to call "this.Listen(...)"
/// </summary>
/// <typeparam name="VncEvent">Type of the event</typeparam>
public interface IVncEventListener<VncEvent> : IVncEventListenerGeneric where VncEvent : struct
{
void OnVncEvent(VncEvent e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment