Skip to content

Instantly share code, notes, and snippets.

@ozergul
Last active Apr 24, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@ozergul 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