IndexOutOfRangeException: Array index is out of range.

Hello I’m trying to make a spawner that spawns enemies at a random location but when I hit play this error will pop up:

IndexOutOfRangeException: Array index is out of range.
Spawner+c__Iterator0.MoveNext () (at Assets/Scripts/Spawner.cs:38)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

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

public class Spawner : MonoBehaviour
{
    public GameObject[] Enemy;
    public Vector3 spawnValues;
    public float spawnWait;
    public float spawnMostWait;
    public float spawnLeastWait;
    public int startWait;
    public bool stop;

    int randEnemy;
   
    void Start ()
    {
        StartCoroutine(waitSpawner());
    }
   
   
    void Update ()
    {
        spawnWait = Random.Range(spawnLeastWait, spawnMostWait);
    }

    IEnumerator waitSpawner ()
    {
        yield return new WaitForSeconds(startWait);

        while (!stop)
        {
            randEnemy = Random.Range(0, 2);

            Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));

            Instantiate(Enemy[randEnemy], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);

            yield return new WaitForSeconds(spawnWait);
        }
    }
}

I need help ASAP. Thank you :slight_smile: !

randEnemyis returning a value that is greater than the number of elements in your Enemyarray, meaning on line 38, you are attempting to instantiate an object that doesn’t exist.

Use Array.Length to avoid this:

randEnemy = Random.Range(0, Enemy.Length);
1 Like

Thank you so much!!