miepzerino
2025-03-29 ad79d9ca49274cc660fc2030a071b24314f0f210
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Inventory : MonoBehaviour
{
    public static Inventory Instance { get; private set; }
    public List<InventorySlot> items = new List<InventorySlot>();
    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;
    }
}