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;
}
}
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;
}
}
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.
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.