Forloop Inside A Forloop

Here is my code. It is suppose to add items to my inventory based on the amount given.

    public void AddItem(GameObject item, int amount)
    {
        for (int i = 0; i < amount; i++)
        {
            for (int x = 0; x < slots.Count; x++)
            {
                if (isFull[x] == false)
                {
                    //additem
                    Instantiate(item, slots[x]);
                    CheckSlots();
                    return;
                }
                else { Debug.Log("Slot Is Full"); }
            }
            Debug.Log("All Slots Are Full");
        }
    }

the forloop with i only seems to run once, only adding one item to my inventory regardless of the amount given.

Line 12 would be responsible for that.

Perhaps a break; ?

Line 16 is also a lie.

What you really want is to just set an amount and count it down one at a time.

Each time you count it down, add one, and if you can’t add one, then say “it’s full” and exit.

I suppose that could be accomplished with an else check as well…

1 Like