事件系统可以通过广播对注册该事件的脚本执行相对应的行为,不用明确接受对象是谁,可以轻松的实现一对多的应用,下面来实现一个简易的事件系统的实现。
1.首先创建脚本 EventManager
public class EventManager
{
//接口。只负责存在在字典中
public interface IRegisterations
{
}
//多个注册
public clasee Registerations<T> : IRegisterations
{
//委托本身可以一对多注册
public Action<T> OnReceives = obj => { };
}
//事件字典
private static Dictionary<Type,IRegisterations> mTyperEventDic = new Dictionary<Type,IRegisterations>();
//注册事件
public static void Register<T>(Action<T> onReceive)
{
var type = typeof(T);
IRegisterations registerations = null;
if(mTypeEventDic.TrtGetValue(type,out registerations ))
{
var reg = registerations as Registerations<T>;
reg.OnReceives += onReceive;
}
else
{
var reg = new Registerations<T>();
reg.OnReceives += onReceive;
mTypeEventDic.Add(type,reg);
}
}
//注销事件
public static void UnRegister<T>(Action<T> onReceive)
{
var type = typeof(T);
IRegisterations registerations = null;
if(mTypeEventDic.TrtGetValue(type,out registerations ))
{
var reg = registerations as Registerations<T>;
reg.OnReceives -= onReceive;
}
}
//发送事件
public static void Send<T>(T t)
{
var type = typeof(T);
IRegisterations registerations = null;
if(mTypeEventDic.TrtGetValue(type,out registerations ))
{
var reg = registerations as Registerations<T>;
reg.OnReceives(t);
}
}
}
2.随后我们就可以在任意脚本中发送和接收事件了。下面为例子。
(1)创建一个事件脚本Event A
public class EventA
{
public int a;
}
(2)创建一个发送事件的脚本,按下A键发送事件。
public class EventSendExample: MonoBehaviour
{
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
EventA eventA = new EventA();
eventA.a = 3;
EventManager.Send(eventA);
}
}
}
(3)创建一个接收事件的脚本,即可接收事件并执行相应的回调函数。
public class EventReciveExample: MonoBehaviour
{
private void OnEnable()
{
//注册事件,标注事件类型以及回调函数
EventManager.Register<EventA>(TestA);
}
private void OnDisable()
{
//注销事件
EventManager.UnRegister<EventA>(TestA);
}
private void TestA()
{
Debug.Log("Send Event Success");
}
}