使用委托和事件在Unity中创建事件管理器(消息系统)

时间:2018-10-29 07:37:45

标签: c# events delegates

统一官方网站上有一个视频教程,名为:

  

Events: Creating a simple messaging system

他们创建了一个事件管理器或消息系统。

我观看了它,它非常有帮助,因此我在游戏上创建了该系统,现在决定不使用UnityEventUnityAction,而是使用delegateevent是更好的性能和良好的做法。因此,这是我的代码[尚未提供{StopListen()函数]:


    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();
        }
    }

在我的Listen()函数中,此行thisEvent = new GameEvents();给我带来了麻烦,我不知道如何解决它! (帮助!):-)

[PS]:

  1. delegateevent相比,UnityEventUnityAction的性能更好吗?
  2. 要使此代码更有效,应该或必须在此代码中添加什么?

1 个答案:

答案 0 :(得分:0)

您必须定义访问委托时应调用的内容,否则,如果不需要执行任何操作,则不需要委托。

像拉姆达一样:

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

或方法:

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

可以看看https://www.codeproject.com/Articles/624575/Delegate-Tutorial-for-Beginners

对于执行时间,我认为最好是进行测试,看看哪些性能更​​好。