我正在尝试使用统一游戏引擎创建一个基本的井字游戏。这是我的代码:
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的原因。
最佳答案
我之前在公共(public)领域使用 Unity 遇到过这个问题。我推测这是由于编辑器界面如何与公共(public)字段集成(编辑器正在清除您的初始化值),但我无法找到文档来支持它。但是,我已经能够通过将初始化代码移动到 Start
函数中来解决这个问题。
但是,如果您仍希望在编辑器中公开它,则可能需要添加额外的逻辑。
void Start ()
{
board = board ?? new int[9] {
0, 0, 0,
0, 0, 0,
0, 0, 0
};
}
或者,我认为如果您只是将变量更改为 private
或 protected
,那么应该将它从编辑器中删除,它也应该可以工作。
关于c# - C# Unity 中数组的长度始终为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957349/