Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Add this to any game object across all scenes

Example usage

public void Start()
{
    EventManager.instance.AddListener("sayHello", OnSayHello);
}

public void OnSayHello()
{
    Debug.Log("Hello!");
}

And then inside of any other script you can trigger the event which will invoke all the registered callbacks

EventManager.instance.Trigger("sayHello");

You can also pass an argument to the callback:

public void Start()
{
    EventManager.instance.AddListener("sayThing", OnSayThing);
}

public void OnSayThing(dynamic thingToSay)
{
    Debug.Log(thingToSay.toString());
}

When you trigger the event, make sure you pass the argument

EventManager.instance.Trigger("sayThing", "Hello world!");

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventManager : MonoBehaviour
{
static public EventManager instance;
private Dictionary<string, Action> _eventDelegates;
private Dictionary<string, Action<dynamic>> _eventDelegatesWithArg;
public void Awake()
{
this._eventDelegates = new Dictionary<string, Action>();
this._eventDelegatesWithArg = new Dictionary<string, Action<dynamic>>();
instance = this;
}
public void AddListener(string eventName, Action callback)
{
if (this._eventDelegates.ContainsKey(eventName))
{
this._eventDelegates[eventName] += callback;
}
else
{
this._eventDelegates.Add(eventName, callback);
}
}
public void AddListener(string eventName, Action<dynamic> callback)
{
if (this._eventDelegatesWithArg.ContainsKey(eventName))
{
this._eventDelegatesWithArg[eventName] += callback;
}
else
{
this._eventDelegatesWithArg.Add(eventName, callback);
}
}
public void RemoveListener(string eventName, Action callback = null)
{
if (this._eventDelegates.ContainsKey(eventName))
{
if (callback != null)
{
this._eventDelegates[eventName] -= callback;
}
else
{
this._eventDelegates.Remove(eventName);
}
}
}
public void RemoveListener(string eventName, Action<dynamic> callback = null)
{
if (this._eventDelegatesWithArg.ContainsKey(eventName))
{
if (callback != null)
{
this._eventDelegatesWithArg[eventName] -= callback;
}
else
{
this._eventDelegatesWithArg.Remove(eventName);
}
}
}
public void Trigger(string eventName)
{
this.Trigger(eventName, null);
}
public void Trigger(string eventName, dynamic arg = null)
{
if (this._eventDelegatesWithArg.ContainsKey(eventName))
{
this._eventDelegatesWithArg[eventName](arg);
}
if (this._eventDelegates.ContainsKey(eventName))
{
this._eventDelegates[eventName]();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.