C#Unity中数组的长度始终为零

时间:2014-02-22 16:56:23

标签: c# arrays unity3d

我正在尝试使用统一游戏引擎创建一个基本的tic tac toe游戏。这是我的代码:

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);
        }
    }
}

但问题是board数组的长度始终为0,并且在尝试访问board数组中的任何值时获得ArrayIndexOutOfBounds异常。 我甚至尝试过不同的创建阵列的方法。结果仍然相同。任何人都可以告诉我数组长度为0的原因。

1 个答案:

答案 0 :(得分:7)

我之前在公共领域遇到过Unity。我推测这是由于编辑器界面如何与公共字段集成(编辑器正在清除你的初始值),但我还是找不到文档来支持它。但是,我已经能够通过将初始化代码移动到Start函数来解决这个问题。

但是,如果您仍希望在编辑器中显示此内容,则可能需要添加额外的逻辑。

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

或者我认为,如果您只是将变量更改为privateprotected,则应将其从编辑器中删除,并且它也应该有效。