Aaron Ge
Aaron Ge

Reputation: 278

Array index going out of range, stopping the for loop it is inside of

My index is still going out of range in my list, inventory, even after I added an if statement that stops inventory [i] from being called once i is greater than the inventory's count (so the inventory items that doesn't exist won't be called), once the inventory[i]'s ID is equal to -1 (The default ID value for empty items), and when number is greater than 1 (To draw the texture only once). I have been stuck on this bug for hours, but nothing I'm trying is working. There were supposed to be a total of 25 boxes, but only 11 were drawn. I noticed that when I change the value of y to two, the error stops The relevant part of my code is below. I deleted the rest for ease of reading. Thank you in advance

void DrawInventory()
{
    int y = 5;
    int x = 5;

    for (int i = 0; i < y; i++) 
    {
        int number = 0;
        number++;
        for (int j = 0; j < x; j++) 
        {
            Rect rect = new Rect (new Vector2 (100 + (i * 60), 0 + (j * 60)), new Vector2 (50, 50));
            GUI.Box (rect, "");
            if (inventory [i].ID != -1 && number == 1 && i < inventory.Count) 
            {
                GUI.DrawTexture (rect, inventory [i].Icon);
                number++;
                print (inventory.Count);
            }   
        }
    }
}

Picture of Error

Upvotes: 0

Views: 75

Answers (1)

Bart van Nierop
Bart van Nierop

Reputation: 4350

In the line if (inventory [i].ID != -1 && number == 1 && i < inventory.Count), inventory[i] is evaluated before i < inventory.Count.

You can fix it by making i < inventory.Count the first check.

Update

After the initial answer, the question asker asked:

Why is it that I must make i < inventory.Count my first check?

This is because the && operator short-circuits. What that means is that whenever the left hand side is false, will not be executed anymore, because false && whatever will never be true.

if (i < inventory.Count && inventory[i].ID) will therefore never execute the right hand side if i is indeed smaller than inventory.Count.

If, however, the condition is if (inventory[i].ID && i < inventory.Count), the left hand side is executed first and that is where the application crashes if i is too large. The right hand side will never be executed.

Upvotes: 1

Related Questions