chore: initial commit
This commit is contained in:
54
Assets/Scripts/Core/Events/EventChannelRegistry.cs
Normal file
54
Assets/Scripts/Core/Events/EventChannelRegistry.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user