Last active
April 24, 2021 15:08
-
-
Save ozergul/226a8a304ad2c4349bafabefd9ce85fc to your computer and use it in GitHub Desktop.
Unity3d Event Manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To trigger event:
to listen event: