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

Unity中RandomObjectSpawner脚本触发IndexOutOfRangeException错误求助

解决Unity随机生成物体的IndexOutOfRangeException错误

错误原因

你遇到的IndexOutOfRangeException是因为代码里的myObjects数组没有在Unity Inspector中赋值,数组长度为0。此时Random.Range(0, myObjects.Length)会返回0,但数组里没有索引为0的元素,导致越界报错。

解决步骤

  1. 将RandomObjectSpawner脚本挂载到场景中的任意GameObject上(比如新建一个空物体)。
  2. 选中挂载了脚本的物体,在Inspector面板找到RandomObjectSpawner组件的myObjects数组:
    • 修改数组长度为你需要的数量(至少1)。
    • 将你想要生成的灌木丛等物体拖拽到数组的元素槽中。

代码优化(可选)

可以在代码中增加数组为空的判断,避免未赋值时触发报错,同时给出提示:

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

public class RandomObjectSpawner : MonoBehaviour
{
    public GameObject[] myObjects;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // 检查数组是否为空,为空则提示并退出
            if (myObjects.Length == 0)
            {
                Debug.LogError("myObjects数组未赋值,请在Inspector面板添加要生成的物体!");
                return;
            }
            
            int randomIndex = Random.Range(0, myObjects.Length);
            Vector3 randomSpawnPosition = new Vector3(Random.Range(-10, 11), 5, Random.Range(-10, 11));
            Instantiate(myObjects[randomIndex], randomSpawnPosition, Quaternion.identity);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:34