62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
|
|
using System.Collections.Generic;
|
|||
|
|
using Sirenix.OdinInspector;
|
|||
|
|
using UnityEngine;
|
|||
|
|
|
|||
|
|
namespace Ichni.Story
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 全局角色注册表(ScriptableObject)。
|
|||
|
|
/// 按 characterId 索引所有 <see cref="CharacterData"/>,
|
|||
|
|
/// 运行时提供带缓存的快速查找。
|
|||
|
|
/// </summary>
|
|||
|
|
[CreateAssetMenu(fileName = "CharacterRegistry", menuName = "Ichni/Story/New/CharacterRegistry")]
|
|||
|
|
public class CharacterRegistry : SerializedScriptableObject
|
|||
|
|
{
|
|||
|
|
[LabelText("Characters")]
|
|||
|
|
[ListDrawerSettings(ShowFoldout = true, DraggableItems = true)]
|
|||
|
|
[InfoBox("将所有角色的 CharacterData 资产拖入此列表,系统运行时会自动按 characterId 建立索引。")]
|
|||
|
|
public List<CharacterData> characters = new List<CharacterData>();
|
|||
|
|
|
|||
|
|
// 运行时缓存,首次 TryGet 时延迟构建
|
|||
|
|
private Dictionary<string, CharacterData> _cache;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 根据 characterId 查找角色数据,找到时返回 true 并通过 out 输出结果。
|
|||
|
|
/// </summary>
|
|||
|
|
public bool TryGet(string characterId, out CharacterData data)
|
|||
|
|
{
|
|||
|
|
if (_cache == null)
|
|||
|
|
BuildCache();
|
|||
|
|
|
|||
|
|
return _cache.TryGetValue(characterId, out data);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 根据 characterId 获取角色数据,未找到时返回 null。
|
|||
|
|
/// </summary>
|
|||
|
|
public CharacterData Get(string characterId)
|
|||
|
|
{
|
|||
|
|
TryGet(characterId, out CharacterData data);
|
|||
|
|
return data;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void BuildCache()
|
|||
|
|
{
|
|||
|
|
_cache = new Dictionary<string, CharacterData>(characters.Count);
|
|||
|
|
|
|||
|
|
foreach (CharacterData character in characters)
|
|||
|
|
{
|
|||
|
|
if (character == null) continue;
|
|||
|
|
if (!string.IsNullOrEmpty(character.characterId))
|
|||
|
|
_cache[character.characterId] = character;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void OnValidate()
|
|||
|
|
{
|
|||
|
|
// Inspector 中修改列表时清除缓存,确保 TryGet 结果始终一致
|
|||
|
|
_cache = null;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|