Files
zeling_v2/Assets/_Game/Scripts/Inventory/ItemDatabaseSO.cs
2026-06-05 18:41:33 +08:00

47 lines
1.6 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.Inventory
{
/// <summary>
/// 道具目录 SO背包系统
/// 全局唯一资产(建议 Assets/_Game/Data/Inventory/ItemDatabase.asset
/// 通过 itemId 查找 <see cref="ItemSO"/> 引用。
/// 由 <see cref="InventoryManager"/> 在拾取 / OnLoad 时查询。
/// 设计对照 <see cref="BaseGames.Equipment.CharmCatalogSO"/>,但内部用字典缓存以支持高频查询。
/// </summary>
[CreateAssetMenu(menuName = "BaseGames/Inventory/ItemDatabase")]
public class ItemDatabaseSO : ScriptableObject
{
[SerializeField] private ItemSO[] _items;
public IReadOnlyList<ItemSO> AllItems => _items;
private Dictionary<string, ItemSO> _index;
/// <summary>按 itemId 查找道具,找不到返回 null。</summary>
public ItemSO Find(string itemId)
{
if (string.IsNullOrEmpty(itemId) || _items == null) return null;
EnsureIndex();
return _index.TryGetValue(itemId, out var item) ? item : null;
}
private void EnsureIndex()
{
if (_index != null) return;
_index = new Dictionary<string, ItemSO>(_items.Length);
foreach (var item in _items)
if (item != null && !string.IsNullOrEmpty(item.itemId))
_index[item.itemId] = item;
}
/// <summary>编辑器修改 _items 后清空索引,下次 Find 重建。</summary>
public void InvalidateIndex() => _index = null;
#if UNITY_EDITOR
private void OnValidate() => _index = null;
#endif
}
}