using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public interface IEventInfo { } public class EventInfo : IEventInfo { public UnityAction actions; public EventInfo( UnityAction action) { actions += action; } } public class EventInfo : IEventInfo { public UnityAction actions; public EventInfo(UnityAction action) { actions += action; } } /// /// 事件中心 单例模式对象 /// 1.Dictionary /// 2.委托 /// 3.观察者设计模式 /// 4.泛型 /// public class EventCenter : BaseManager { //key —— 事件的名字(比如:怪物死亡,玩家死亡,通关 等等) //value —— 对应的是 监听这个事件 对应的委托函数们 private Dictionary eventDic = new Dictionary(); /// /// 添加事件监听 /// /// 事件的名字 /// 准备用来处理事件 的委托函数 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 AddEventListener(string name, UnityAction action) { //有没有对应的事件监听 //有的情况 if (eventDic.ContainsKey(name)) { (eventDic[name] as EventInfo).actions += action; } //没有的情况 else { eventDic.Add(name, new EventInfo(action)); } } /// /// 移除对应的事件监听 /// /// 事件的名字 /// 对应之前添加的委托函数 public void RemoveEventListener(string name, UnityAction action) { if (eventDic.ContainsKey(name)) (eventDic[name] as EventInfo).actions -= action; } /// /// 移除不需要参数的事件 /// /// /// public void RemoveEventListener(string name, UnityAction action) { if (eventDic.ContainsKey(name)) (eventDic[name] as EventInfo).actions -= action; } /// /// 事件触发 /// /// 哪一个名字的事件触发了 public void EventTrigger(string name, T info) { //有没有对应的事件监听 //有的情况 if (eventDic.ContainsKey(name)) { //eventDic[name](); if((eventDic[name] as EventInfo).actions != null) (eventDic[name] as EventInfo).actions.Invoke(info); //eventDic[name].Invoke(info); } } /// /// 事件触发(不需要参数的) /// /// public void EventTrigger(string name) { //有没有对应的事件监听 //有的情况 if (eventDic.ContainsKey(name)) { //eventDic[name](); if ((eventDic[name] as EventInfo).actions != null) (eventDic[name] as EventInfo).actions.Invoke(); //eventDic[name].Invoke(info); } } /// /// 清空事件中心 /// 主要用在 场景切换时 /// public void Clear() { eventDic.Clear(); } }