Inventory adding items when no space

Hey guys,
So i got a little problem here. Even tho i am looping through all children in slot manager to check if they got children(items) so i know if that slot is clear or not and then add the item, when all slots are full it just starts adding items out of that parent. Like it doesnt make any sense. Here’s the code:

private void createSlots (){
        for (int i = 0; i < slotAmount; i++)
        {
            slotObject = (GameObject)Instantiate (slotPrefab);
            slotObject.transform.SetParent (slotParent.transform);

        }
    }
    public void giveItem(int itemid,int ammount){
        Item.ItemProperties item = GameObject.FindGameObjectWithTag ("InventoryDatabase").GetComponent<InventoryDatabase> ().getItem (itemid);
        GameObject itemSlot = Instantiate (itemPrefab);
        foreach (Transform i in slotParent.transform) {
            if (i != null) {
                if (i.transform.childCount == 0) {
                    itemSlot.transform.SetParent (i);
                    itemSlot.transform.GetComponent<RawImage> ().texture = item.ItemSprite;
                    itemSlot.transform.position = new Vector3 (0, 0, 0);
                    itemSlot.transform.localPosition = new Vector3 (0, 0, 0);
                    itemSlot.transform.GetComponent<RectTransform> ().offsetMin = new Vector2 (0, 0);
                    itemSlot.transform.GetComponent<RectTransform> ().offsetMax = new Vector2 (0, 0);
                    Debug.Log (i);
                    break;
                }
            }
        }

       
    }

You could set a constraint in an if statement,

If (Items.Length <= Inventory space)
{
// add items
}
else
{
// do nothing
}
1 Like

In GiveItem you create the item regardless, either only create it when you find a valid slot or delete it if you never find a slot.