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