using System; using System.Collections.Generic; using System.Linq; using UnityEngine; [Serializable] public class Inventory : MonoBehaviour { public List additionalSlots; public GameObject itemContainerPrefab; private List _inventorySlots; private void Awake() { _inventorySlots = new List(); foreach (var inventorySlot in additionalSlots) { inventorySlot.SetParentInventory(this); _inventorySlots.Add(inventorySlot); } } private void OnEnable() { var inventorySlotsInChildren = GetComponentsInChildren(); foreach (var inventorySlot in inventorySlotsInChildren) { inventorySlot.SetParentInventory(this); _inventorySlots.Add(inventorySlot); } } public bool AddItem(ItemData item) { if (item.canStack) { return AddItem(ConvertToInventoryItem(item)); } return AddToFirstOpenSlot(item.gameObject); } public bool AddItem(InventoryItem item) { //Stacks the item if it already exists in the inventory. foreach (var inventorySlot in _inventorySlots.Where(inventorySlot => inventorySlot.ContainsItem(item.GetItemid()))) { inventorySlot.GetItem().ChangeCount(item.Count); return true; } return AddToFirstOpenSlot(item.gameObject); } private bool AddToFirstOpenSlot(GameObject item) { foreach (var inventorySlot in _inventorySlots.Where(inventorySlot => !inventorySlot.ContainsItem())) { inventorySlot.AssignItem(item); return true; } return false; } private InventoryItem ConvertToInventoryItem(ItemData item) { var inventoryItem = Instantiate(itemContainerPrefab, transform); itemContainerPrefab.GetComponent().itemPrefab = item.gameObject; return inventoryItem.gameObject.GetComponent(); } }