97 lines
3.1 KiB
C#
97 lines
3.1 KiB
C#
![]() |
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
using System.Threading.Tasks;
|
||
|
using UnityEngine;
|
||
|
|
||
|
namespace DDD
|
||
|
{
|
||
|
public class InventoryManager : Singleton<InventoryManager>, IManager
|
||
|
{
|
||
|
private Dictionary<string, ItemData> _itemDataLookup;
|
||
|
private Dictionary<string, InventoryItemData> _inventoryItemDatas;
|
||
|
|
||
|
public void PreInit()
|
||
|
{
|
||
|
|
||
|
}
|
||
|
|
||
|
public Task Init()
|
||
|
{
|
||
|
return Task.CompletedTask;
|
||
|
}
|
||
|
|
||
|
public void PostInit()
|
||
|
{
|
||
|
InitializeItemData();
|
||
|
}
|
||
|
|
||
|
private void InitializeItemData()
|
||
|
{
|
||
|
var itemDataSo = DataManager.Instance.ItemDataSo;
|
||
|
|
||
|
Debug.Assert(itemDataSo != null, "itemDataSo != null");
|
||
|
|
||
|
_itemDataLookup = itemDataSo.GetDataList()
|
||
|
.Where(item => !string.IsNullOrEmpty(item.Id))
|
||
|
.ToDictionary(item => item.Id, item => item);
|
||
|
|
||
|
_inventoryItemDatas = new Dictionary<string, InventoryItemData>(itemDataSo.GetDataCount());
|
||
|
}
|
||
|
|
||
|
public bool AddItem(string id, int quantity = 1)
|
||
|
{
|
||
|
if (!_itemDataLookup.ContainsKey(id))
|
||
|
{
|
||
|
Debug.LogError($"[Inventory] 등록되지 않은 아이템 ID: {id}");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
if (_inventoryItemDatas.TryGetValue(id, out var itemData))
|
||
|
{
|
||
|
itemData.Quantity += quantity;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
_inventoryItemDatas[id] = new InventoryItemData(id, quantity);
|
||
|
}
|
||
|
|
||
|
EventBus.Broadcast(new InventoryChangedEvent());
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public bool RemoveItem(string id, int quantity = 1)
|
||
|
{
|
||
|
if (!_inventoryItemDatas.TryGetValue(id, out var itemData))
|
||
|
{
|
||
|
Debug.LogError($"[Inventory] 등록되지 않은 아이템 ID: {id}");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
if (itemData.Quantity < quantity)
|
||
|
{
|
||
|
Debug.LogWarning($"[Inventory] 보유 수량보다 삭제하는 수량이 더 많습니다 " +
|
||
|
$"{id}, 보유 수량 : {itemData.Quantity}, 삭제 수량 : {quantity}");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
itemData.Quantity -= quantity;
|
||
|
|
||
|
if (itemData.Quantity <= 0)
|
||
|
{
|
||
|
_inventoryItemDatas.Remove(id);
|
||
|
}
|
||
|
|
||
|
EventBus.Broadcast(new InventoryChangedEvent());
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public IReadOnlyDictionary<string, InventoryItemData> InventoryItems => _inventoryItemDatas;
|
||
|
public bool TryGetItemData(string id, out ItemData itemData) => _itemDataLookup.TryGetValue(id, out itemData);
|
||
|
public int GetItemCount(string id) => _inventoryItemDatas.TryGetValue(id, out var itemData) ? itemData.Quantity : 0;
|
||
|
public ItemData GetItemDataByIdOrNull(string id)
|
||
|
{
|
||
|
_itemDataLookup.TryGetValue(id, out var itemData);
|
||
|
return itemData;
|
||
|
}
|
||
|
}
|
||
|
}
|