我在Unity中执行代码时总是出现以下问题:
ArgumentOutOfRangeException:索引超出范围。必须是非负的并且小于集合的大小。 参数名称:index
我在 Unity 编辑器中直接设置的属性 Grid,x 和 y 的值为 10。
公开课世界:MonoBehaviour {
public Room[,] Dungeon { get; set; }
public Vector2 Grid;
private void Awake()
{
Dungeon = new Room[(int)Grid.x, (int)Grid.y];
StartCoroutine(GenerateFloor());
}
public IEnumerator GenerateFloor()
{
for (int x = 0; x < Grid.x; x++)
{
for (int y = 0; y < Grid.y; y++)
{
Dungeon[x, y] = new Room
{
RoomIndex = new Vector2(x, y)
};
}
}
yield return new WaitForSeconds(3);
Vector2 exitLocation = new Vector2((int)Random.Range(0, Grid.x), (int)Random.Range(0, Grid.y));
Dungeon[(int)exitLocation.x, (int)exitLocation.y].Exit = true;
Dungeon[(int)exitLocation.x, (int)exitLocation.y].Empty = false;
Debug.Log("Exit is at: " + exitLocation); }}
希望你能帮我解决这个问题
答案 0 :(得分:0)
如果不调试代码,很难看到这样的错误。但一般来说,尽量打破公共 Vector2 Grid; 2 个 int 变量并使用它们,因此不需要显式转换为 int,如果您想要 x==y,您的代码将变得非常可读,那么我们可以在 Awake 中进行测试并且不会意外地询问错误的值.并且 Vector2 exitLocation 可以替换为 Vector2Int 或 2 个变量。