Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

IndexOutOfRangeException: Array index is out of range. (Spawning enemies at a random location)

Discussion in 'Scripting' started by arabellemagdamit, Oct 8, 2018.

  1. arabellemagdamit

    arabellemagdamit

    Joined:
    Sep 4, 2018
    Posts:
    4
    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+<waitSpawner>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)


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Spawner : MonoBehaviour
    6. {
    7.     public GameObject[] Enemy;
    8.     public Vector3 spawnValues;
    9.     public float spawnWait;
    10.     public float spawnMostWait;
    11.     public float spawnLeastWait;
    12.     public int startWait;
    13.     public bool stop;
    14.  
    15.     int randEnemy;
    16.  
    17.     void Start ()
    18.     {
    19.         StartCoroutine(waitSpawner());
    20.     }
    21.  
    22.  
    23.     void Update ()
    24.     {
    25.         spawnWait = Random.Range(spawnLeastWait, spawnMostWait);
    26.     }
    27.  
    28.     IEnumerator waitSpawner ()
    29.     {
    30.         yield return new WaitForSeconds(startWait);
    31.  
    32.         while (!stop)
    33.         {
    34.             randEnemy = Random.Range(0, 2);
    35.  
    36.             Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1, Random.Range(-spawnValues.z, spawnValues.z));
    37.  
    38.             Instantiate(Enemy[randEnemy], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);
    39.  
    40.             yield return new WaitForSeconds(spawnWait);
    41.         }
    42.     }
    43. }
    44.  
    I need help ASAP. Thank you :) !
     
  2. FernandoHC

    FernandoHC

    Joined:
    Feb 6, 2018
    Posts:
    338
    Your enemy array seems to not have that number of enemies the random is providing.
    Make sure you are assigning enemies through the inspector and that you have as much enemies in that array as the the random number generated.