- Home /
Question by
Blenovator · Feb 27, 2014 at 07:53 PM ·
c#script errorsimple
Simple Coding Error Help - C# - Following Packt Book
Got this error following a simple tutorial in the packt book - Unity Android Game Development By Example.
Its a simple game of TicTacToe it seems my boardIndex is not right...
I can't work it out - any help would be greatly appreciated.
Error Code: IndexOutOfRangeException: Array index is out of range. TicTacToeControl.OnGUI () (at Assets/TicTacToeControl.cs:18)
Script:
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;y++) {
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 ? "O" : "";
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;
}
}
Comment
sorry for the rubbish formating.
Line 18 referenced in the error code is the string owner line (i think)
Answer by zharik86 · Feb 27, 2014 at 08:04 PM
You mistake in cycle for. See, you write:
for(int y=0;y<3;y++) {
for(int x=0;x<3;y++) { // mistake y++
...
Change to:
for(int y=0;y<3;y++) {
for(int x=0;x<3;x++) { // change to x++
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Creating a timer for combat (C#) 1 Answer
Flip over an object (smooth transition) 3 Answers