1
votes

There is a video tutorial on unity official website called:

Events: Creating a simple messaging system.

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] :

  1. Is delegate and event have better performance then UnityEvent and UnityAction ?
  2. What more should be or must be add to this code, to make it more efficient?
1

1 Answers

0
votes

You must define what should invoked when the delegate is accessed, otherwise if nothing should be done the delegate is not necessary.

Like a lamda:

thisEvent = new GameEvents(() => { Console.WriteLine("TODO");});

Or a method:

thisEvent = new GameEvents(Target);
private void Target()
{
     throw new NotImplementedException();
}

may be have a look at https://www.codeproject.com/Articles/624575/Delegate-Tutorial-for-Beginners

For execution time, I think best is to make a test and see what performs better.