Unity 简单事件系统的实现

事件系统可以通过广播对注册该事件的脚本执行相对应的行为,不用明确接受对象是谁,可以轻松的实现一对多的应用,下面来实现一个简易的事件系统的实现。

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");
	}
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值