加载中...

unity---事件中心

耦合性低,统一管理

image

代码

image

注册事件

image

当对象被销毁后,需要删除已经注册的事件
image

触发事件

image

移除事件

image

切换场景时需要清空事件

image

当我们要给事件添加参数时

注册事件的类
image
image

优化

利用接口继承优化,避免装箱拆箱
(引用类型和值类型之间的转换)

image
image

完整代码(最终形态)

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();
    }
}

测试代码

posted @ 2022-04-19 20:59  lxp_blog  阅读(294)  评论(0编辑  收藏  举报