using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HJDFrameWork { public class EventManager :MonoSingleton { [Header("已注册事件名")] public List _EventList=new List(); private Dictionary mEvents = new Dictionary(); private interface IEvent { } //BaseEvent和泛型版本的BaseEvent 分别封装了对应的Action委托 private class BaseEvent : IEvent { public Action OnEvent; } private class BaseEvent : IEvent { public Action OnEvent; } /// /// 注册事件 /// public void Register(string name, Action onEvent) { //如果当前的事件字典中 存在当前名字的事件对象 if (mEvents.TryGetValue(name, out IEvent e)) { //就使用as关键字 把父类转化为对应子类 增加注册即可 if (e is BaseEvent) (e as BaseEvent).OnEvent += onEvent; else throw new Exception("注册失败 请使用 Register 进行注册"); } //如果事件字典中不存在当前名字的事件 那就添加一个对象并为其增加一个注册 else { mEvents.Add(name, new BaseEvent() { OnEvent = onEvent }); _EventList.Add(name); } } /// /// 注册事件 /// public void Register(string name, Action onEvent) { //泛型注册方法实现类似 if (mEvents.TryGetValue(name, out IEvent e)) { if (e is BaseEvent) (e as BaseEvent).OnEvent += onEvent; else throw new Exception("注册失败 请使用 Register 进行注册"); } else mEvents.Add(name, new BaseEvent() { OnEvent = onEvent }); } /// /// 注销事件 /// public void UnRegister(string name, Action onEvent) { if (!mEvents.TryGetValue(name, out IEvent e)) return; //注销事件也是差不多 如果当前的事件字典中 存在当前名字的事件对象 就从当前事件对象移除一个注册 if (e is BaseEvent) (e as BaseEvent).OnEvent -= onEvent; else throw new Exception("注销失败 请使用 UnRegister 进行注销"); } /// /// 注销事件 /// public void UnRegister(string name, Action onEvent) { if (!mEvents.TryGetValue(name, out IEvent e)) return; if (e is BaseEvent) (e as BaseEvent).OnEvent -= onEvent; else throw new Exception("注销失败 请使用 UnRegister 进行注销"); } /// /// 触发事件 /// public void Trigger(string name) { if (!mEvents.TryGetValue(name, out IEvent e)) return; //触发事件也很像 如果当前的事件字典中 存在当前名字的事件 那就执行当前事件对象中注册的所有事件 if (e is BaseEvent) (e as BaseEvent).OnEvent?.Invoke(); else throw new Exception("触发失败 请使用 Trigger 进行触发"); } /// /// 触发事件 /// public void Trigger(string name, T data) { //泛型版本的触发事件实现类似 不过多解说 if (!mEvents.TryGetValue(name, out IEvent e)) return; if (e is BaseEvent) (e as BaseEvent).OnEvent?.Invoke(data); else throw new Exception("触发失败 请使用 Trigger 进行触发"); } } }