运行此代码后:
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 平台获得解决方案。
看起来您正在尝试访问
colors
中不存在的元素。查看totalBlocks的值,在运行脚本之前,colors
中至少需要有那么多元素。