You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity IndexOutOfRangeException异常求助:数组索引越界问题

解决Unity脚本中的IndexOutOfRangeException异常

问题描述

运行脚本时触发以下异常:

IndexOutOfRangeException: Index was outside the bounds of the array.
Blocks.Place () (at Assets/Scripts/Blocks.cs:49)

异常原因

异常出现在newBlock.GetComponent<SpriteRenderer>().color = colors[currentRow];这一行。当生成的行数(currentRow)超过你在Inspector中给colors数组设置的元素数量时,就会触发数组索引越界异常。

解决方案

方案1:保证colors数组长度匹配所需行数

先计算需要的总行数:总行数 = Mathf.CeilToInt((float)totalBlocks / blocksPerRow),然后在Inspector面板中给colors数组添加至少对应数量的颜色元素。比如总块数20、每行5块,需要4行,那colors数组至少要有4个颜色。

方案2:添加边界处理,避免索引越界

修改设置颜色的代码,要么循环使用已有颜色,要么超出时用默认颜色:

// 循环复用colors数组中的颜色
Color targetColor = colors[currentRow % colors.Length];
// 或者超出数组长度时使用默认颜色(比如白色)
// Color targetColor = currentRow < colors.Length ? colors[currentRow] : Color.white;
newBlock.GetComponent<SpriteRenderer>().color = targetColor;

方案3:提前校验参数,避免运行时出错

在Place方法开头添加参数检查,提前拦截不合理的配置:

void Place()
{
    Reset();

    if (blocksPerRow <= 0)
    {
        Debug.LogError("blocksPerRow必须大于0,请检查Inspector配置");
        return;
    }
    if (colors == null || colors.Length == 0)
    {
        Debug.LogError("colors数组不能为空,请在Inspector中添加至少一种颜色");
        return;
    }

    // 后续原有代码...
}

完整修改后的代码

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;

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

        // 参数校验
        if (blocksPerRow <= 0)
        {
            Debug.LogError("blocksPerRow必须大于0,请检查Inspector配置");
            return;
        }
        if (colors == null || colors.Length == 0)
        {
            Debug.LogError("colors数组不能为空,请在Inspector中添加至少一种颜色");
            return;
        }

        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;
            
            // 循环使用颜色,避免索引越界
            Color targetColor = colors[currentRow % colors.Length];
            newBlock.GetComponent<SpriteRenderer>().color = targetColor;

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

内容的提问来源于stack exchange,提问作者Muhammad_Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 02:06:01