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