using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { public ItemSlot[] itemSlots; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { } // we'll set this up to only try to add one item to the inventory at a time for now // there won't be stacked items in the wild for right now public bool AddItem(Item item) { // first try to stack for (int i = 0; i < itemSlots.Length; i++) { if (itemSlots[i] != null) { if (itemSlots[i].item == item.id && itemSlots[i].quantity < item.maxStack) { itemSlots[i].quantity += 1; return true; } } } // no stack to add to, try to find an empty slot for (int i = 0; i < itemSlots.Length; i++) { if (itemSlots[i] == null) { itemSlots[i] = new ItemSlot(); itemSlots[i].quantity = 1; itemSlots[i].item = item.id; return true; } } // no open slots, no open stacks, we can't add the item return false; } public bool RemoveItemQuantity(ItemIdEnum itemId, int quantity) { if (GetItemQuantity(itemId) >= quantity) { int currentQuantity = quantity; for (int i = 0; i < itemSlots.Length; i++) { if (itemSlots[i] != null && itemSlots[i].item == itemId) { // we are trying to remove less items than what exists in the current // stack, so just subtract from the stack if (currentQuantity < itemSlots[i].quantity) { itemSlots[i].quantity -= currentQuantity; break; } else if (currentQuantity == itemSlots[i].quantity) { // we have exactly enough in the current slot, so nullify it and // exit itemSlots[i] = null; break; } else { // we don't have enough in the stack, but we DO have enough in our // inventory. nullify the stack, subtract that number from the current // count, and move to the next item currentQuantity -= itemSlots[i].quantity; itemSlots[i] = null; } } } return true; } else { return false; } } public int GetItemQuantity(ItemIdEnum itemId) { int itemCount = 0; foreach (ItemSlot slot in itemSlots) { if (slot != null && slot.item == itemId) { itemCount += slot.quantity; } } return itemCount; } #region Inventory Save/Load public void SaveInventory(ref InventorySaveData data) { data.itemSlots = itemSlots; } public void LoadInventory(InventorySaveData data) { if (data.itemSlots != null) { itemSlots = data.itemSlots; } else { Debug.Log("new slots"); itemSlots = new ItemSlot[8]; } } #endregion } [System.Serializable] public class ItemSlot { public int quantity; public ItemIdEnum item; } [System.Serializable] public struct InventorySaveData { public ItemSlot[] itemSlots; }