Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IndexOutOfRangeException: Index was outside the bounds of the array RandomObjectSpawner.Update () (at Assets/Scripts/RandomObjectSpawner.cs:21)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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


    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading