Iam following packt book tutorial for creating tictactoe game. I encountered a index out of range exception. i searched fro answers everywhere and checked my code multiple times but am not able to find the error in my code.pls help!

using UnityEngine;
using System.Collections;

public class TicTacToeControl : MonoBehaviour {

public SquareState[] board = new SquareState[9];
public bool xTurn = true;

public void OnGUI() {
   float width = 75;
   float height = 75;
   
   
   
   for(int y=0; y<3 ; y++){
        for(int x=0; x<3 ; x++){
		
		int boardIndex = (y*3)+x;
		
		
		Rect square = new Rect (x*width, y*height, width,height);
		
		string owner = board[boardIndex] == SquareState.XControl ? "X" :
		               board[boardIndex] == SquareState.OControl ? "Y" : " ";
					   
		if (GUI.Button(square,owner))SetControl(boardIndex);
					   }
					   }
}

public void SetControl(int boardIndex){
    if(boardIndex<0 || boardIndex >= board.Length) return;
	board[boardIndex] = xTurn ? SquareState.XControl : SquareState.OControl;
	xTurn = !xTurn;
}

}

the error report is IndexOutOfRangeException: Array index is out of range.
TicTacToeControl.OnGUI () (at Assets/TicTacToeControl.cs:23)

Packt books are notoriously poorly-edited… I’m guessing that line 23 is:

string owner = board[boardIndex] == 0 ? "X" : board[boardIndex] == 1 ? "Y" : " ";

which, IMO, is a pretty ugly line of code, but I can’t see why it would generate an index out of range exception - your boardIndex int loops from 0-8, and your board is a SquareState[9] so that should be fine. When you look at the TicTacToeControl component in the inspector pane, can you confirm that it definitely says 9 for the “Size” of the Board element?