Skip to content

Instantly share code, notes, and snippets.

@ozergul
Last active April 24, 2021 15:08
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 ozergul/226a8a304ad2c4349bafabefd9ce85fc to your computer and use it in GitHub Desktop.
Save ozergul/226a8a304ad2c4349bafabefd9ce85fc to your computer and use it in GitHub Desktop.
Unity3d Event Manager
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class EventManager : MonoBehaviour
{
private Dictionary<string, Action<EventParam>> eventDictionary;
private static EventManager eventManager;
public static EventManager instance
{
get
{
if (!eventManager)
{
eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
}
else
{
eventManager.Init();
}
}
return eventManager;
}
}
void Init()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<string, Action<EventParam>>();
}
}
public static void StartListening(string eventName, Action<EventParam> listener)
{
Action<EventParam> thisEvent;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
//Add more event to the existing one
thisEvent += listener;
//Update the Dictionary
instance.eventDictionary[eventName] = thisEvent;
}
else
{
//Add event to the Dictionary for the first time
thisEvent += listener;
instance.eventDictionary.Add(eventName, thisEvent);
}
}
public static void StopListening(string eventName, Action<EventParam> listener)
{
if (eventManager == null) return;
Action<EventParam> thisEvent;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
//Remove event from the existing one
thisEvent -= listener;
//Update the Dictionary
instance.eventDictionary[eventName] = thisEvent;
}
}
public static void TriggerEvent(string eventName, [Optional] EventParam eventParam)
{
instance.eventDictionary[eventName](eventParam);
}
}
public struct EventParam
{
public dynamic param;
}
@ozergul
Copy link
Author

ozergul commented Apr 24, 2021

To trigger event:

EventParam eventParam = new EventParam();
eventParam.param = "test";
EventManager.TriggerEvent(Events.SHOW_TRUE_MODAL, eventParam);

to listen event:

 void OnEnable ()
    {
        EventManager.StartListening (Events.SHOW_TRUE_MODAL, ShowTrueModalListener);
    }

    void OnDisable ()
    {
        EventManager.StopListening (Events.SHOW_TRUE_MODAL, ShowTrueModalListener);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment