- Home /
How do I fix Index Out Of Range Exception error
I was making a code to highlight the allowed moves for a chess game. Then when I tried to run it in unity I got this error: "IndexOutOfRangeException: Array index is out of range." Anyone know how to fix('if (moves[i, j]' is the line with the error) .
public void HighlightAllowedMoves(bool[,] moves)
{
for(int i = 0; i <= 8; i++)
{
for (int j = 0; j <= 8; j++)
{
if (moves[i, j])
{
GameObject go = GetHighlightObject();
go.SetActive(true);
go.transform.position = new Vector3(i + 0.5f, 0, j + 0.5f);
}
}
}
}
As a chess board has 8x8 fields, try this:
for(int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
Answer by nj4242 · Sep 02, 2016 at 09:19 AM
Generally @masonb21, Array out of Range Exception error occurs when you are trying to access item which is either a negative index number or index exceeding (n-1) range of any array. Here, when you using array note that it starts with 0 and ends with the (n-1) which is the -1 length of the array.
In your context, you said you are creating a chess(which is always 8x8 matrix). So, what you are doing wrong is that you are trying to access an invalid index at the last iteration of your array, Think of what you are doing in the last iteration, when i or j <= 8 (which is ofcourse 8 in last iteration, you are actually incrementing it to go at 9, which is definately out of ranges of your array.Length
. Because your array ranges from (0 to 8), if you are not talking about chess, because in the context of chess as an array it should be (0-7).
Simply try to replace and use this code :
public void HighlightAllowedMoves(bool[,] moves)
{
for(int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (moves[i, j])
{
GameObject go = GetHighlightObject();
go.SetActive(true);
go.transform.position = new Vector3(i + 0.5f, 0, j + 0.5f);
}
}
}
}
Or to simplify your confusion just create two array , with its length 8, and in use
for (int i = 0; i < yourArray.Length ; i++)
{
// your code.
}
Cheers.