EventManager.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using UnityEngine;
  2. using UnityEngine.Events;
  3. using System.Collections;
  4. using System.Collections.Generic;
  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. UnityEvent thisEvent = null;
  28. if (instance.eventDictionary.TryGetValue(eventName, out thisEvent)) {
  29. thisEvent.AddListener(listener);
  30. } else {
  31. thisEvent = new UnityEvent();
  32. thisEvent.AddListener(listener);
  33. instance.eventDictionary.Add(eventName, thisEvent);
  34. }
  35. }
  36. public static void StopListening(string eventName, UnityAction listener) {
  37. if (eventManager == null) return;
  38. UnityEvent thisEvent = null;
  39. if (instance.eventDictionary.TryGetValue(eventName, out thisEvent)) {
  40. thisEvent.RemoveListener(listener);
  41. }
  42. }
  43. public static void TriggerEvent(string eventName) {
  44. UnityEvent thisEvent = null;
  45. if (instance.eventDictionary.TryGetValue(eventName, out thisEvent)) {
  46. thisEvent.Invoke();
  47. }
  48. }
  49. }