There is a video tutorial on unity official website called:
They create a Event Manager or Messaging System.
I watch it and it was very helpful so I create that system on my game and now decided to instead of using UnityEvent
and UnityAction
use delegate
and event
which is better performance and good practice. So here is my code [StopListen()
function not included yet]:
public class EventManager : MonoBehaviour { public delegate void GameEvents(); public event GameEvents onGameEvent; private static EventManager _instance = null; public static EventManager Instance { get { if (_instance == null) { _instance = FindObjectOfType(typeof(EventManager)) as EventManager; } if(!_instance) { Debug.LogError("Put a GameObject with this scrip attach to it on your scene."); } else { _instance.InitializeEventDictionary(); } return _instance; } } private Dictionary eventsDictionary; void InitializeEventDictionary() { if (eventsDictionary == null) eventsDictionary = new Dictionary(); } public void Listen(string eventName, GameEvents gameEvent) { GameEvents thisEvent = null; if (Instance.eventsDictionary.TryGetValue(eventName, out gameEvent)) { thisEvent += gameEvent; } else { thisEvent = new GameEvents(); thisEvent += gameEvent; Instance.eventsDictionary.Add(eventName, thisEvent); } } public void TriggerEvent(string eventName) { GameEvents thisEvent; if(Instance.eventsDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.Invoke(); } }
In my Listen()
function this line thisEvent = new GameEvents();
gets me in trouble and I don't know how to fix it! (Help!) :-)
[PS] :
- Is
delegate
andevent
have better performance thenUnityEvent
andUnityAction
? - What more should be or must be add to this code, to make it more efficient?