x


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;
    }
}
more ▼

asked Feb 27 at 07:53 PM

Blenovator gravatar image

Blenovator
0

sorry for the rubbish formating.

Line 18 referenced in the error code is the string owner line (i think)

Feb 27 at 07:45 PM Blenovator
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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++
more ▼

answered Feb 27 at 08:04 PM

zharik86 gravatar image

zharik86
3k 18 917 38

Hero!!

Where are my glasses...

Feb 27 at 08:10 PM Blenovator

@Blenovator Check this answer if I helped you.:)

Feb 28 at 07:47 AM zharik86
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x9714
x3976
x171
x87

asked: Feb 27 at 07:53 PM

Seen: 175 times

Last Updated: Feb 28 at 07:47 AM