EventManager.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. public class EventManager : MonoBehaviour {
  6. private Dictionary<string, UnityEvent> eventDictionary;
  7. private static EventManager eventManager;
  8. public static EventManager Instance {
  9. get {
  10. if (!eventManager) {
  11. eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
  12. if (!eventManager) {
  13. Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
  14. } else {
  15. eventManager.Init();
  16. }
  17. }
  18. return eventManager;
  19. }
  20. }
  21. void Init() {
  22. if (eventDictionary == null) {
  23. eventDictionary = new Dictionary<string, UnityEvent>();
  24. }
  25. }
  26. public static void StartListening(string eventName, UnityAction listener) {
  27. if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) {
  28. thisEvent.AddListener(listener);
  29. } else {
  30. thisEvent = new UnityEvent();
  31. thisEvent.AddListener(listener);
  32. Instance.eventDictionary.Add(eventName, thisEvent);
  33. }
  34. }
  35. public static void StopListening(string eventName, UnityAction listener) {
  36. if (eventManager == null) return;
  37. if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) {
  38. thisEvent.RemoveListener(listener);
  39. }
  40. }
  41. public static void TriggerEvent(string eventName) {
  42. if (Instance.eventDictionary.TryGetValue(eventName, out UnityEvent thisEvent)) {
  43. thisEvent.Invoke();
  44. }
  45. }
  46. }