Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- internal class Slot
- {
- public GameObject slot;
- public Item item;
- public int amount;
- public int size;
- }
- public class Inventory : MonoBehaviour
- {
- #region Data
- private GameObject _slotHolder;
- private int _slotAmount;
- private GameObject[] _slots;
- private bool _visible = false;
- private readonly List<Slot> _slotList = new List<Slot>();
- public GameObject inventory;
- #endregion
- #region Events
- private void Awake()
- {
- if (inventory == null)
- {
- Debug.LogError("No Inventory object assigned!");
- return;
- }
- _slotHolder = inventory.transform.Find("SlotHolder").gameObject;
- if (_slotHolder == null)
- {
- Debug.LogError("Inventory object does not contain a SlotHolder object");
- return;
- }
- _GrabInventorySlots();
- }
- #endregion
- #region API
- public bool IsVisible()
- {
- return _visible;
- }
- public void ToggleVisibility()
- {
- _visible = !_visible;
- inventory.SetActive(_visible);
- }
- public void AddItem(Item aItem, int aAmount = 1)
- {
- // Check if the item is stackable and the inventory contains this item already
- bool contains = _slotList.Any(x => x.item.id == aItem.id);
- if (contains)
- {
- var slots = _slotList.Where(x => x.item.id == aItem.id).ToArray();
- foreach (var slot in slots)
- {
- if ((slot.amount + aAmount) < slot.size)
- {
- // Enough space, insert directly
- slot.amount += aAmount;
- return;
- }
- if ((slot.amount + aAmount) > slot.size)
- {
- // Check if enough empty slots are free for remainder
- int remainder = (slot.amount + aAmount) - slot.size;
- if (remainder > slot.size)
- {
- // Need more than one slot
- }
- else
- {
- // Remainded should fit into one slot
- }
- }
- }
- }
- }
- private Slot _GetFreeSlot()
- {
- foreach (Slot slot in _slotList)
- {
- if (slot.amount == 0)
- {
- return slot;
- }
- }
- return null;
- }
- private Slot _GetFreeSlotContainingItem(Item aItem)
- {
- foreach (Slot slot in _slotList)
- {
- if (slot.item.id == aItem.id)
- {
- if (slot.amount < slot.size)
- {
- return slot;
- }
- }
- }
- return null;
- }
- private void _GrabInventorySlots()
- {
- _slotAmount = _slotHolder.transform.childCount;
- _slots = new GameObject[_slotAmount];
- for (int i = 0; i < _slotAmount; i++)
- {
- _slots[i] = _slotHolder.transform.GetChild(i).gameObject;
- Slot item = new Slot
- {
- slot = _slots[i],
- item = null,
- amount = 0,
- size = _slots[i].GetComponent<InventorySlot>().slotSize
- };
- _slotList.Add(item);
- }
- Debug.Log("Found " + _slotAmount + " inventory slots");
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement