I watched a tutorial to make an inventory and now I rewrote some code to make it better for my game, but can someone help me make a detect item script for my slots? Basically I want to be able to detect if an item is in a slot and if there is an item in that slot, move to the next
I have 2 scripts for the inventory that involve slots.
[CreateAssetMenu(menuName = "My Assets/Inventory")]
public class Inventory : ScriptableObject
{
private Slot[] _slots;
[SerializeField]
private Slot slot_;
public void Init(Slot[] slots)
{
_slots = slots;
}
public void AddItem(Item itemToBeAdded, Item startingItem = null)
{
int amountInStack = itemToBeAdded.amountInStack;
List<Item> stackableItems = new List<Item>();
List<Slot> emptySlots = new List<Slot>();
slot_.CheckForItem();
if (startingItem && startingItem.itemID == itemToBeAdded.itemID && startingItem.amountInStack < startingItem.maxStackSive)
stackableItems.Add(startingItem);
foreach (Slot i in _slots)
{
if (i.slotsItem)
{
Item z = i.slotsItem;
if (z.itemID == itemToBeAdded.itemID && z.amountInStack < z.maxStackSive && z != startingItem)
stackableItems.Add(z);
}
else
{
emptySlots.Add(i);
}
}
foreach (Item i in stackableItems)
{
int amountThatCanbeAdded = i.maxStackSive - i.amountInStack;
if (amountInStack <= amountThatCanbeAdded)
{
i.amountInStack += amountInStack;
Destroy(itemToBeAdded.gameObject);
return;
}
else
{
i.amountInStack = i.maxStackSive;
amountInStack -= amountThatCanbeAdded;
}
}
itemToBeAdded.amountInStack = amountInStack;
if (emptySlots.Count > 0)
{
itemToBeAdded.transform.parent = emptySlots[0].transform;
itemToBeAdded.gameObject.SetActive(false);
}
}
}
Then heres the actual slot script:
using UnityEngine.UI;
public class Slot : MonoBehaviour
{
public Item slotsItem;
Sprite defaultSprite;
Text amountText;
private void Start()
{
defaultSprite = GetComponent<Image>().sprite;
amountText = transform.GetChild(0).GetComponent<Text>();
}
private void Update()
{
CheckForItem();
}
public void CheckForItem()
{
if(transform.childCount > 1)
{
Item slotsItem = transform.GetChild(1).GetComponent<Item>();
GetComponent<Image>().sprite = slotsItem.itemSprite;
if(slotsItem.amountInStack > 1)
{
amountText.text = slotsItem.amountInStack.ToString();
}
}
else
{
slotsItem = null;
GetComponent<Image>().sprite = defaultSprite;
amountText.text = "";
}
}
}
Can anyone help?