using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events;
public class GameEventManager : SingleTon<GameEventManager> { private interface IEventHelp {
}
private class EventHelp : IEventHelp { public event UnityAction Action;
public void AddCall(UnityAction action) { Action += action; }
public void Call() { Action?.Invoke(); }
public void RemoveCall(UnityAction action) { Action -= action; } }
private class EventHelp<T> : IEventHelp { public event UnityAction<T> Action;
public void AddCall(UnityAction<T> action) { Action += action; }
public void Call() { Action?.Invoke(default(T)); }
public void RemoveCall(UnityAction<T> action) { Action -= action; } }
private Dictionary<string, IEventHelp> eventManager = new Dictionary<string, IEventHelp>();
// 添加事件监听 public void AddEventListening(string eventName, UnityAction action) { if (!eventManager.ContainsKey(eventName)) { eventManager[eventName] = new EventHelp(); } ((EventHelp)eventManager[eventName]).AddCall(action); }
// 添加带参数的事件监听 public void AddEventListening<T>(string eventName, UnityAction<T> action) { if (!eventManager.ContainsKey(eventName)) { eventManager[eventName] = new EventHelp<T>(); } ((EventHelp<T>)eventManager[eventName]).AddCall(action); }
// 删除事件监听 public void RemoveEvent(string eventName, UnityAction action) { if (eventManager.ContainsKey(eventName)) { var eventHelp = eventManager[eventName] as EventHelp; if (eventHelp != null) { eventHelp.RemoveCall(action); } } }
// 删除带参数的事件监听 public void RemoveEvent<T>(string eventName, UnityAction<T> action) { if (eventManager.ContainsKey(eventName)) { var eventHelp = eventManager[eventName] as EventHelp<T>; if (eventHelp != null) { eventHelp.RemoveCall(action); } } }
// 触发事件 public void InvokeEvent(string eventName) { if (eventManager.ContainsKey(eventName)) { var eventHelp = eventManager[eventName] as EventHelp; if (eventHelp != null) { eventHelp.Call(); } } }
// 触发带参数的事件 public void InvokeEvent<T>(string eventName, T param) { if (eventManager.ContainsKey(eventName)) { var eventHelp = eventManager[eventName] as EventHelp<T>; if (eventHelp != null) { eventHelp.Call(); } } } }