Unity事件中心
为什么要运用事件中心
降低程序耦合性,减小程序复杂度

举个例子
老师发布了一个问题,但是老师要是每个人去询问就会花费大量的时间,十分不方便,要是同学们能在老师发布问题后主动告知老师,那就很方便了。

如何在Unity中实现
首先我们创建3个脚本CallBack(事件回调)EventCenter(事件管理的中心)EventType(事件的标签)

CallBack
根据需要定义多个不同参数的委托

EventCenter
首先定义一个字典来存储
private static Dictionary<EventType,Delegate> m_dic=new Dictionary<EventType, Delegate>();
EventType通过枚举来存放方法标签(这里的方法标签为了一会儿测试使用,可以忽略)

事件中心需要对应的3个方法
1.添加监听
2.移除监听
3.广播事件
1.添加监听

2.移除监听

3.广播事件

这样简单的事件中心就实现完成了
下面是事件中心的完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class EventCenter
{
private static Dictionary<EventType,Delegate> m_dic=new Dictionary<EventType, Delegate>();
public static void AddListen(EventType eventType,CallBack callBack)
{
if (!m_dic.ContainsKey(eventType))
{
m_dic.Add(eventType,null);
}
Delegate d = m_dic[eventType];
if (d!=null&& d.GetType()!=callBack.GetType())
{
throw new Exception("类型不同");
}
m_dic[eventType] = (CallBack) m_dic[eventType] + callBack;
}
public static void RemoveListen(EventType eventType, CallBack callBack)
{
if (m_dic.ContainsKey(eventType))
{
Delegate d = m_dic[eventType];
if (d==null)
{
throw new Exception("没有对应的事件");
}
else if (d.GetType()!=callBack.GetType())
{
throw new Exception("类型不同");
}
}
else
{
throw new Exception("没有对应的事件");
}
m_dic[eventType] = (CallBack) m_dic[eventType] - callBack;
}
public static void Broadcast(EventType eventType)
{
Delegate d;
if (m_dic.TryGetValue(eventType,out d))
{
CallBack callBack = (CallBack) d;
if (callBack!=null)
{
callBack();
}
else
{
throw new Exception("CallBack为空");
}
}
}
}
下面进行测试
当按下按钮就让文字现实出来

这两个测试脚本中的代码


当点击按钮时文本就显示出来了
本文深入探讨Unity事件中心的运用,旨在降低程序耦合性,简化复杂度。通过实例讲解,详细介绍了事件中心的实现原理及操作方法,包括添加监听、移除监听和广播事件等关键步骤。


被折叠的 条评论
为什么被折叠?



