IndexOutOfRangeException: Array index is out of range.

Hey all! So halfway into development of this game, I got this error that I just can’t solve. I’m super new to C# as well so I might have written some unnecessary super long codes that could have been done in a single line. I’m getting there… hopefully.

So the error “IndexOutOfRangeException: Array index is out of range.” occurs at the line where I’ve written “ERROR HERE” (This is just for pointing out the location of the error is not actually in the code).

bool MakeOneMoveDownIndex(Tile[] LineOfTiles)
	{
		for (int i = 0; i < LineOfTiles.Length - 1; i++)
		{
			//MOVE BLOCK
			if (LineOfTiles *.Number == 0 && LineOfTiles [i + 1].Number != 0)*
  •  	{*
    

_ LineOfTiles .Number = LineOfTiles [i + 1].Number;_
* LineOfTiles [i + 1].Number = 0;*
* return true;*
* }*
* //Blue + Red + Green = White*
_ else if (LineOfTiles .Number != 0 &&
LineOfTiles .Number == 33 /blue/ &&
ERROR HERE: LineOfTiles [i + 1].Number == 11 /red/ &&
LineOfTiles [i + 2].Number == 22 /green/ &&
LineOfTiles .mergedThisTurn == false && LineOfTiles [i + 1].mergedThisTurn == false && LineOfTiles [i + 2].mergedThisTurn == false)
* {
LineOfTiles .Number = 77; /white/
LineOfTiles [i + 1].Number = 0;
LineOfTiles [i + 2].Number = 0;
LineOfTiles .mergedThisTurn = true;
//GameOver();
return true;
}*

If you require any more code let me know because this error is in the 300s line. But I don’t think other lines of code are relevant to this error because they aren’t array related.
In the line after //MOVE BLOCK, I’ve tried changing this:
> if (LineOfTiles .Number == 0 && LineOfTiles [i + 1].Number != 0)
to this:
> if (LineOfTiles .Number == 0 && LineOfTiles [i + 2].Number != 0)
but it didn’t work…
Thanks for taking out the time to help me out! :slight_smile:_

LineOfTiles [i + 1]

This is your problem,
if you hit the last index, and you do + 1 that index doesn’t exist so you get the error.

you shoud do it like this:

if (LineOfTiles *.Number == 0 && LineOfTiles.Length > i + 1 &&  LineOfTiles [i + 1].Number != 0)*

But then you still have a chance that your last index can be 0 so you would have to make an extra check and do something in there:
if ((LineOfTiles.Length -1) == i && LineOfTiles*.Number == 0) {*
// last tile is 0
// do something
}
Note: you will have to check for LineOfTiles.Length > i + 1 everywhere where you use the i + 1