Home > Net >  IndexOutOfRangeException: Index was outside the bounds of the array RandomObjectSpawner.Update () (a
IndexOutOfRangeException: Index was outside the bounds of the array RandomObjectSpawner.Update () (a

Time:07-26

So i have this script that i am trying to use to spawn random objects in random positions in my game. but i have this error "IndexOutOfRangeException: Index was outside the bounds of the array. RandomObjectSpawner.Update () (at Assets/Scripts/RandomObjectSpawner.cs:21)"

These are the objects i want to spawn when i click the middle bush

this is the script i'm using:

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

public class RandomObjectSpawner : MonoBehaviour
{

    public GameObject[] myObjects;



    void Update()
    {
        if (Input.GetMouseButtonDown(0))

        {

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


    }
}

CodePudding user response:

I have a wild hunch. I guess your script is attached to multiple game objects and in one of them the game objects are not assigned to the array. so check all other game objects to see if RandomObjectSpawner is not assigned to any other gameobject.

CodePudding user response:

Try initializing your array like this and see if the problem happens again:

 public GameObject[] myObjects = new GameObject[] { };

Alternatively you can attach your debugger to Unity, set a breakpoint to this line:

int randomIndex = Random.Range(0, myObjects.Length);

And see step by step (1) what's the index that has been generated, (2) what the actual length of the array is.

  • Related