Question

I'm trying to create a basic tic tac toe game using unity game engine. Here's my code :

public int[] board = new int[9] {
    0, 0, 0, 
    0, 0, 0, 
    0, 0, 0
};
public bool xTurn = true;

public void OnGUI() {
    float width = 75;
    float height = 75;
    for (int y = 0; y < 3; y++) {
        Debug.Log("Value of y = " + y);
        for (int x = 0; x < 3; x++) {
            Debug.Log("Length of array = " + board.Length);
            int boardIndex = (y * 3) + x;
            Rect square = new Rect(x * width, y * height, width, height);
            Debug.Log ("Value of boardIndex = " + boardIndex + " value of x = " + x);
            string owner = board[boardIndex] == 1 ? "X" :
                board[boardIndex] == -1 ? "O" : "";
            if(GUI.Button(square, owner))
                SetControl(boardIndex);
        }
    }
}

But the problem is that the length of board array is always 0 and getting a ArrayIndexOutOfBounds Exception when trying to access any value inside the board array. I've even tried different ways of creating the array. still the same result. Can anyone tell me the reason for length of array being 0.

Était-ce utile?

La solution

I've run into this with Unity before on public fields. I've speculated that it's due to how the editor interface integrates with public fields (editor is clearing your intialized value) but I haven't been able to find documentation to back that up. I have, however, been able to work around this by moving the initialization code into the Start function.

However, you may have to add extra logic if you still want this exposed within the editor.

void Start ()
{
    board = board ?? new int[9] {
      0, 0, 0, 
      0, 0, 0, 
      0, 0, 0
    };
}

Alternatively I think if you simply change the variable to private or protected that should remove it from the editor and it should also work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top