66 lines
2.5 KiB
C#
66 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class EventSvcHandler
|
|
{
|
|
private bool GetNeedDebugLog() => CombatScenarioEventOS.Instance.GetNeedDebugLog();
|
|
private readonly Dictionary<EVENT_ENUM, Delegate> actionBroadcast = new(); // 广播事件地址
|
|
|
|
// ================================
|
|
// 1. 定义事件类型
|
|
// ================================
|
|
private readonly Dictionary<EVENT_ENUM, Type> actionBindMap = new() // 事件类型类型绑定
|
|
{
|
|
// ========== 系统事件 ==========
|
|
{ EVENT_ENUM.EVENT_LET_OS_DEAL_CARD, typeof(EVENT_STRUCT.STRUCT_EVENT_OS_DEAL_CARD) }, // 系统发牌事件
|
|
|
|
// ========== 卡牌事件 ==========
|
|
{ EVENT_ENUM.EVENT_LET_CARD_DRAW_CARD, typeof(EVENT_STRUCT.STRUCT_EVENT_CARD_DRAW_CARD) } // 卡牌抽牌事件
|
|
};
|
|
|
|
private bool GET_DEFINE_EVENT(EVENT_ENUM eventName, Type t, string msg)
|
|
{
|
|
if (!actionBindMap.TryGetValue(eventName, out var value))
|
|
{
|
|
if (GetNeedDebugLog()) Debug.LogError($"{msg}: 未绑定的数据类型[{eventName}]");
|
|
return false;
|
|
}
|
|
|
|
if (value == t) return true;
|
|
if (GetNeedDebugLog()) Debug.LogError($"{msg}: 未响应的数据类型[{eventName}]");
|
|
return false;
|
|
}
|
|
|
|
// ================================
|
|
// 2. 注册回调,强类型检查
|
|
// ================================
|
|
public void EVENT_REGISTER<T>(EVENT_ENUM eventName, Action<T> callback)
|
|
{
|
|
if (!GET_DEFINE_EVENT(eventName, typeof(T), "注册事件失败")) return;
|
|
actionBroadcast.TryAdd(eventName, null);
|
|
actionBroadcast[eventName] = (Action<T>)actionBroadcast[eventName] + callback;
|
|
}
|
|
|
|
// ================================
|
|
// 3. 注销回调
|
|
// ================================
|
|
public void EVENT_UNREGISTER<T>(EVENT_ENUM eventName, Action<T> callback)
|
|
{
|
|
if (!GET_DEFINE_EVENT(eventName, typeof(T), "注销事件失败")) return;
|
|
actionBroadcast[eventName] = (Action<T>)actionBroadcast[eventName] - callback;
|
|
if (actionBroadcast[eventName] == null) actionBroadcast.Remove(eventName);
|
|
}
|
|
|
|
// ================================
|
|
// 4. 触发事件, 强类型检查
|
|
// ================================
|
|
public void EVENT_DISPATCH<T>(EVENT_ENUM eventName, T param)
|
|
{
|
|
if (!GET_DEFINE_EVENT(eventName, typeof(T), "触发事件失败")) return;
|
|
if (actionBroadcast.TryGetValue(eventName, out var action))
|
|
{
|
|
(action as Action<T>)?.Invoke(param);
|
|
}
|
|
}
|
|
} |