Files
zeling_v2/Assets/Scripts/Core/Events/EventChannelRegistry.cs
2026-05-08 11:04:00 +08:00

55 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
using UnityEngine;
namespace BaseGames.Core.Events
{
/// <summary>
/// 运行时事件频道注册表。
/// 在 Persistent 场景 Awake 时由 EventChannelRegistrar 注册所有频道 SO
/// 供不能持有 [SerializeField] 的动态对象CharmEffect SO 等)按类型名查找频道。
/// </summary>
public class EventChannelRegistry : MonoBehaviour, IEventChannelRegistry
{
public static EventChannelRegistry Instance { get; private set; }
private readonly Dictionary<string, ScriptableObject> _channels = new();
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
/// <summary>由 EventChannelRegistrar 在场景初始化时批量注册频道 SO。</summary>
public void Register(string key, ScriptableObject channel)
=> _channels[key] = channel;
/// <summary>
/// 按 key 查找频道。key = SO 资产文件名(不含扩展名),如 "EVT_HitConfirmed"。
/// </summary>
public T Get<T>(string key) where T : ScriptableObject
{
if (_channels.TryGetValue(key, out var ch) && ch is T typed) return typed;
Debug.LogError($"[EventChannelRegistry] Key '{key}' not found or wrong type ({typeof(T).Name}).");
return null;
}
/// <summary>尝试获取频道,不报错。</summary>
public bool TryGet<T>(string key, out T channel) where T : ScriptableObject
{
if (_channels.TryGetValue(key, out var ch) && ch is T typed)
{
channel = typed;
return true;
}
channel = null;
return false;
}
}
}