using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class EventManager : MonoBehaviour { private Dictionary 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(); } } public static void StartListening(string eventName, UnityAction listener) { if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) { thisEvent.AddListener(listener); } else { thisEvent = new UnityEvent(); thisEvent.AddListener(listener); Instance.eventDictionary.Add(eventName, thisEvent); } } public static void StopListening(string eventName, UnityAction listener) { if (eventManager == null) return; if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) { thisEvent.RemoveListener(listener); } } public static void TriggerEvent(string eventName) { if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) { thisEvent.Invoke(); } } }