unity---事件中心
耦合性低,统一管理
代码
注册事件
当对象被销毁后,需要删除已经注册的事件
触发事件
移除事件
切换场景时需要清空事件
当我们要给事件添加参数时
注册事件的类
优化
利用接口继承优化,避免装箱拆箱
(引用类型和值类型之间的转换)
完整代码(最终形态)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public interface IEventInfo //父类接口
{
}
public class EventInfo<T>:IEventInfo{
public UnityAction<T> actions; //带参
public EventInfo(UnityAction<T> action){
actions += action;
}
}
public class EventInfo:IEventInfo{
public UnityAction actions; //不带参
public EventInfo(UnityAction action){
actions += action;
}
}
public class EventCenter : Singleton<EventCenter>
{
// Start is called before the first frame update
private Dictionary<string,IEventInfo > eventDic=new Dictionary<string, IEventInfo>();
// Update is called once per frame
public void AddEventListener<T>(string name,UnityAction<T> action){
if(eventDic.ContainsKey(name)){
(eventDic[name] as EventInfo<T>).actions+=action;
}else {
eventDic.Add(name,new EventInfo<T>(action));
}
}
public void AddEventListener(string name,UnityAction action){
if(eventDic.ContainsKey(name)){
(eventDic[name] as EventInfo).actions+=action;
}else {
eventDic.Add(name,new EventInfo(action));
}
}
public void EventTrigger<T>(string name,T info){
if(eventDic.ContainsKey(name)){
if((eventDic[name] as EventInfo<T>).actions!= null)
( eventDic[name] as EventInfo<T> ).actions(info);
}
}
public void EventTrigger(string name){
if(eventDic.ContainsKey(name)){
if((eventDic[name] as EventInfo).actions!= null)
( eventDic[name] as EventInfo).actions();
}
}
public void RemoveEventListener<T>(string name,UnityAction<T> action){
if(eventDic.ContainsKey(name)){
(eventDic[name] as EventInfo<T>).actions-=action;
}
}
public void RemoveEventListener(string name,UnityAction action){
if(eventDic.ContainsKey(name)){
(eventDic[name] as EventInfo).actions-=action;
}
}
public void Clear(){
eventDic.Clear();
}
}