77 lines
2.1 KiB
C#
77 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using UnityEngine;
|
|
|
|
[Serializable]
|
|
public class Inventory : MonoBehaviour
|
|
{
|
|
public List<InventorySlot> additionalSlots;
|
|
|
|
public GameObject itemContainerPrefab;
|
|
|
|
private List<InventorySlot> _inventorySlots;
|
|
|
|
private void Awake()
|
|
{
|
|
_inventorySlots = new List<InventorySlot>();
|
|
foreach (var inventorySlot in additionalSlots)
|
|
{
|
|
inventorySlot.SetParentInventory(this);
|
|
_inventorySlots.Add(inventorySlot);
|
|
}
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
var inventorySlotsInChildren = GetComponentsInChildren<InventorySlot>();
|
|
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<InventoryItem>().itemPrefab = item.gameObject;
|
|
|
|
return inventoryItem.gameObject.GetComponent<InventoryItem>();
|
|
}
|
|
} |