Unity 指数超出范围问题

问题描述 投票:0回答:1

运行此代码后:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Blocks : MonoBehaviour
{
    public GameObject blockPrefab;

    [Space]
    public int totalBlocks;

    public float xGap;

    public float yGap;

    public int blocksPerRow;

    public Color[] colors;

    // Start is called before the first frame update
    void Reset()
    {
        List<GameObject> blocksToDestroy = new List<GameObject>();
        for (int i = 0; i < transform.childCount; i++)
            blocksToDestroy.Add(transform.GetChild(i).gameObject);

        foreach (GameObject block in blocksToDestroy)
            DestroyImmediate(block);

        blocksToDestroy.Clear();
    }

    [ContextMenu("Place")]

    void Place()
    {
        Reset();

        int currentBlocksInRow = 0;
        int currentRow = 0;
        for (int i = 0; i < totalBlocks; i++)
        {
            Vector3 position = transform.position;
            position.x += xGap * currentBlocksInRow;
            position.y += yGap * currentRow;

            GameObject newBlock = Instantiate(blockPrefab, position, Quaternion.identity);
            newBlock.transform.parent = transform;
            newBlock.GetComponent<SpriteRenderer>().color = colors[currentRow];


            currentBlocksInRow++;
            if (currentBlocksInRow >= blocksPerRow)
            {
                currentRow++;
                currentBlocksInRow = 0;
            }
        }
    }
}

出现错误:

IndexOutOfRangeException:索引超出了数组的范围。 Blocks.Place ()(位于 Assets/Scripts/Blocks.cs:49)

我正在尝试解决这个问题,我希望我能从 stackoverflow 平台获得解决方案。

c# unity-game-engine debugging
1个回答
0
投票

看起来您正在尝试访问

colors
中不存在的元素。查看totalBlocks的值,在运行脚本之前,
colors
中至少需要有那么多元素。

© www.soinside.com 2019 - 2024. All rights reserved.