Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Created December 19, 2020 20:46
Show Gist options
  • Save grimmdev/95eea40b6716ffc09378f1e08cdfeade to your computer and use it in GitHub Desktop.
Save grimmdev/95eea40b6716ffc09378f1e08cdfeade to your computer and use it in GitHub Desktop.
Message System Dispatcher for Unity
using System;
[Serializable]
public class Event
{
public string name;
public Action method;
public Event(string n, Action m)
{
name = n;
method = m;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public class EventManager
{
private static List<Event> Listeners = new List<Event>();
private static List<ObjectEvent> ObjectListeners = new List<ObjectEvent>();
public static void AddListener(string name, Action method)
{
if (method != null)
{
if (!Listeners.Exists(l => l.name == name && l.method == method))
{
Listeners.Add(new Event(name, method));
}
}
}
public static void RemoveListener(string name, Action method)
{
if (method != null)
{
if (Listeners.Exists(l => l.name == name && l.method == method))
{
Event tmp = Listeners.Single(l => l.name == name && l.method == method);
Listeners.Remove(tmp);
}
}
}
public static void SendMessage(string name)
{
if (Listeners.Count > 0)
{
for (int i = 0; i < Listeners.Count; i++)
{
if (Listeners[i].name == name)
{
Listeners[i].method.Invoke();
}
}
}
}
public static void AddListener(string name, Action<object> method)
{
if (method != null)
{
if (!ObjectListeners.Exists(l => l.name == name && l.method == method))
{
ObjectListeners.Add(new ObjectEvent(name, method));
}
}
}
public static void RemoveListener(string name, Action<object> method)
{
if (method != null)
{
if (ObjectListeners.Exists(l => l.name == name && l.method == method))
{
ObjectEvent tmp = ObjectListeners.Single(l => l.name == name && l.method == method);
ObjectListeners.Remove(tmp);
}
}
}
public static void SendMessage(string name, object param)
{
if (ObjectListeners.Count > 0)
{
for (int i = 0; i < ObjectListeners.Count; i++)
{
if (ObjectListeners[i].name == name)
{
ObjectListeners[i].method.Invoke(param);
}
}
}
}
}
using System;
[Serializable]
public class ObjectEvent
{
public string name;
public Action<object> method;
public ObjectEvent(string n, Action<object> m)
{
name = n;
method = m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment