Files

99 lines
2.2 KiB
C#
Raw Permalink Normal View History

2026-06-04 20:14:47 +03:00
using System;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public static Inventory Instance { get; private set; }
[Serializable]
public class InventorySlot
{
public ItemData item;
public int amount;
}
[SerializeField] private List<InventorySlot> slots = new List<InventorySlot>();
public IReadOnlyList<InventorySlot> Slots => slots;
public event Action OnInventoryChanged;
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
public void AddItem(ItemData item, int amount)
{
AddItem(item, amount, true);
}
public void AddItem(ItemData item, int amount, bool notifyQuestManager)
{
if (item == null || amount <= 0)
{
return;
}
InventorySlot slot = slots.Find(candidate => candidate.item == item);
if (slot == null)
{
slot = new InventorySlot { item = item, amount = 0 };
slots.Add(slot);
}
slot.amount += amount;
OnInventoryChanged?.Invoke();
if (notifyQuestManager && QuestManager.Instance != null)
{
QuestManager.Instance.OnItemCollected(item, amount);
}
}
public bool RemoveItem(ItemData item, int amount)
{
if (item == null || amount <= 0)
{
return false;
}
InventorySlot slot = slots.Find(candidate => candidate.item == item);
if (slot == null || slot.amount < amount)
{
return false;
}
slot.amount -= amount;
if (slot.amount <= 0)
{
slots.Remove(slot);
}
OnInventoryChanged?.Invoke();
return true;
}
public bool HasItem(ItemData item, int amount)
{
return GetAmount(item) >= amount;
}
public int GetAmount(ItemData item)
{
if (item == null)
{
return 0;
}
InventorySlot slot = slots.Find(candidate => candidate.item == item);
return slot == null ? 0 : slot.amount;
}
}