using System.Collections; using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { public static Inventory Instance { get; private set; } public List items = new List(); public int maxInventorySize = 20; private void Awake() { if (Instance == null) { Instance = this; } else { Destroy(gameObject); } } public bool AddItem(Item item, int quantity = 1) { if (items.Count >= maxInventorySize && !item.isStackable) return false; InventorySlot existingSlot = items.Find(slot => slot.item.itemName == item.itemName); if (existingSlot != null && item.isStackable) { if (existingSlot.quantity + quantity <= item.maxStackSize) { existingSlot.quantity += quantity; return true; } else { int remainingQuantity = item.maxStackSize - existingSlot.quantity; existingSlot.quantity = item.maxStackSize; return AddItem(item, quantity - remainingQuantity); } } else { if (items.Count < maxInventorySize) { items.Add(new InventorySlot(item, quantity)); return true; } return false; } } public void RemoveItem(Item item, int quantity = 1) { InventorySlot existingSlot = items.Find(slot => slot.item.itemName == item.itemName); if (existingSlot != null) { if (existingSlot.quantity > quantity) { existingSlot.quantity -= quantity; } else { items.Remove(existingSlot); } } } } [System.Serializable] public class InventorySlot { public Item item; public int quantity; public InventorySlot(Item item, int quantity) { this.item = item; this.quantity = quantity; } }