Index out of bound, but I dont see the problem

Hi! I alway get a index out of bound exception with my code. In unity the index of an array starts with 0 right? array.length returns the amounet of values an array can store right? What is wrong here?

public bool [,] gameGrid = new bool [5,10];
    public bool [] visitedLocations = new bool [10];


for (int i=0; i <= 9; i++)
        {
            visitedLocations[i] = false;

            for (int k = 0; k <= 4; k++)
            {
                gameGrid[k, i] = false;
            }
        }

2 things:

What does your object’s inspector look like? If this is on a MonoBehaviour, then whatever the inspector shows will overwrite your defaults that you have on lines 1 and 2 here. I would guess the array is not as long as you have on your default value.

Second, there’s no reason to hardcode the lengths in your for loop. Do this:

for (int i=0; i <= visitedLocations.Length; i++)
        {
            visitedLocations[i] = false;
            for (int k = 0; k <= gameGrid.GetLength(0); k++)
            {
                gameGrid[k, i] = false;
            }
        }
3 Likes

Looks fine to me.Check which line it is. Maybe it’s in a different spot. If it is add a line before the error like: Debug.Log(“k=”+L+" i="+i);. Maybe it crashes on 0,0, which means the array is totally the wrong size.

It’s also a little micer to use k<5 than k<=4. That way the array size is right there in the line. Later it can become k<A.length when you don’t know the size ahead of time.

1 Like

Everything Owen and Praetor said above, plus my standard array bounds blurb for you:

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

I’d tack onto Praetor’s code above and only do the inner loop if (i < grid.GetLength(1)) {

1 Like

I thought PB was dead-on: public arrays are in the Inspector and are always size 0 unless you type new values into the Inspector. But 2D arrays aren’t shown in the Inspector., It’s probably safer to follow Unity’s guidelines and NEW them in Start or Awake.

Inspector was the problem. Thank you! :slight_smile:

If I do (HideInInspector) does it solve the problem in the future?

No but either private or [NonSerialized] would solve it.

1 Like