项目开发过程中经常会用到代理事件,为方便管理,避免代码混乱,需要一个总的事件管理器:
using UnityEngine;using System.Collections;using System.Collections.Generic;using System;public class EventManager{ private static Dictionary >> eventDic = new Dictionary >>(); /// /// 添加事件 /// /// /// public static void AddEvent(EventType type, Actionact) { if (eventDic.ContainsKey(type)) { if(!eventDic[type].Contains(act)) { eventDic[type].Add(act); } }else { List > list = new List >(); eventDic.Add(type, list); list.Add(act); } } /// /// 移除事件 /// /// public static void RemoveEvent(EventType type) { if (eventDic.ContainsKey(type)) { eventDic.Remove(type); } } public static void RemoveEvent(EventType type, Actionact) { if (eventDic.ContainsKey(type)) { if (eventDic[type].Contains(act)) { eventDic[type].Remove(act); } } } /// /// 触发事件 /// /// /// public static void TriggerEvent(EventType type , T data) { if (eventDic.ContainsKey(type)) { List> list = eventDic[type]; foreach (var callback in list) { callback(data); } } }}public enum EventType{ None = 0, Event1 = 1, Event2 = 2,}