c# - 使用委托和事件在 Unity 中创建事件管理器(消息系统)
问题描述
unity官网上有一个视频教程叫:
他们创建了一个事件管理器或消息系统。
我看了它,它非常有帮助,所以我在我的游戏中创建了这个系统,现在决定不使用UnityEvent
和UnityAction
使用delegate
,event
这是更好的性能和良好的实践。所以这是我的代码[StopListen()
尚未包含功能]:
公共类 EventManager : MonoBehaviour { 公共代表无效 GameEvents(); 公共事件 GameEvents onGameEvent; 私有静态 EventManager _instance = null; 公共静态 EventManager 实例 { 得到 { 如果(_instance == null) { _instance = FindObjectOfType(typeof(EventManager)) 作为 EventManager; } 如果(!_实例) { Debug.LogError("将带有此脚本的游戏对象附加到您的场景中。"); } 别的 { _instance.InitializeEventDictionary(); } 返回_实例; } } 私人字典事件字典; 无效初始化事件字典() { if (eventsDictionary == null) eventsDictionary = new Dictionary(); } 公共无效听(字符串事件名称,游戏事件游戏事件) { 游戏事件 thisEvent = null; if (Instance.eventsDictionary.TryGetValue(eventName, out gameEvent)) { 这个事件 += 游戏事件; } 别的 { thisEvent = new GameEvents(); 这个事件 += 游戏事件; Instance.eventsDictionary.Add(eventName, thisEvent); } } 公共无效触发事件(字符串事件名称) { 游戏事件 thisEvent; if(Instance.eventsDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.Invoke(); } }
在我的Listen()
函数中,这条线thisEvent = new GameEvents();
给我带来了麻烦,我不知道如何解决它!(帮助!) :-)
[PS]:
delegate
那么和有event
更好的性能吗?UnityEvent
UnityAction
- 应该或必须在此代码中添加什么以使其更高效?
解决方案
您必须定义在访问委托时应该调用什么,否则如果什么都不做,则不需要委托。
像一个lamda:
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
对于执行时间,我认为最好是进行测试,看看什么表现更好。