一、类的描述:
1、在CallBack类中定义了委托,有无参的,1个参数的…到有5个参数的。这相当于U3d中的Action类。
public delegate void CallBack();
public delegate void CallBack<T>(T arg);
public delegate void CallBack<T, X>(T arg1, X arg2);
public delegate void CallBack<T, X, Y>(T arg1, X arg2, Y arg3);
public delegate void CallBack<T, X, Y, Z>(T arg1, X arg2, Y arg3, Z arg4);
public delegate void CallBack<T, X, Y, Z, W>(T arg1, X arg2, Y arg3, Z arg4, W arg5);
2、EventType类中的枚举存放了事件码,后续有需要的话可以自己新加。
3、最主要的是EventCenter类,定义了不同参数的添加监听(AddListener)、移除监听(RemoveListener)和消息广播(Broadcast)。
AddListener(事件码,委托);
底层实现:在一个字典Dictionary<EventType,Delegate>以键(事件码)、值(委托)的形式,存放了所有的事件,广播的时候就会以传参的形式更新事件中的参数。
public static void AddListener(EventType eventType, CallBack callBack)
{
OnListenerAdding(eventType, callBack);
m_EventTable[eventType] = (CallBack)m_EventTable[eventType] + callBack;
}
public static void RemoveListener(EventType eventType, CallBack callBack)
{
OnListenerRemoving(eventType, callBack);
m_EventTable[eventType] = (CallBack)m_EventTable[eventType] - callBack;
OnListenerRemoved(eventType);
}
二、使用示例:
2.1 添加事件监听
在Awake()中添加监听,如果调用的委托方法中需要传入参数,就要在AddListener<>的泛型中填入对应的参数类型,如果需要传入一个String类型,那就是AddListener
private void Awake()
{
EventCenter.AddListener<string>(EventType.ShowText,Show);
}
2.2 移除事件监听
private void OnDestroy()
{
EventCenter.RemoveListener<string>(EventType.ShowText,Show);
}
2.3 委托的方法,参数的类型与数量要和事件监听的一样
void Show(string str)
{
GetComponent<Text>().text = str;
}
2.4 广播 (广播事件码)
Broadcast(事件码,委托中的参数 [])
void Start () {
GetComponent<Button>().onClick.AddListener(()=> {
EventCenter.Broadcast(EventType.ShowText,"Hello,World !");
});
}