Search Unity

Other IndexOutOfRangeException: Index was outside the bounds of the array.

Discussion in 'Scripting' started by thecapitankaty, Oct 25, 2022.

  1. thecapitankaty

    thecapitankaty

    Joined:
    Nov 21, 2020
    Posts:
    11
    Error: IndexOutOfRangeException: Index was outside the bounds of the array.


    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class EnemySpawner : MonoBehaviour
    7. {
    8.     public GameObject[] spawnPoints;
    9.     GameObject currentPoint;
    10.     int index;
    11.  
    12.     public GameObject[] enemies;
    13.     public float minTimeBtwSpawns;
    14.     public float maxTimeBtwSpawns;
    15.     public bool canSpawn;
    16.     public float spawnTime;
    17.     public int enemiesInRoom;
    18.     public bool spawnerDone;
    19.     public GameObject spawnerDoneGameObject;
    20.  
    21.     private void Start()
    22.     {
    23.         Invoke("SpawnEnemy", 0.5f);
    24.     }
    25.  
    26.     private void Update()
    27.     {
    28.         if (canSpawn)
    29.         {
    30.             spawnTime -= Time.deltaTime;
    31.             if (spawnTime < 0)
    32.             {
    33.                 spawnTime = 3;
    34.             }
    35.         }
    36.     }
    37.  
    38.     void SpawnEnemy()
    39.     {
    40.         index = Random.Range(0, spawnPoints.Length);
    41.         currentPoint = spawnPoints[index];
    42.         float timeBtwSpawns = Random.Range(minTimeBtwSpawns, maxTimeBtwSpawns);
    43.  
    44.         if (canSpawn)
    45.         {
    46.             Instantiate(enemies[Random.Range(0, enemies.Length)], currentPoint.transform.position, Quaternion.identity);
    47.             enemiesInRoom++;
    48.         }
    49.  
    50.         Invoke("SpawnEnemy", timeBtwSpawns);
    51.         if (spawnerDone)
    52.         {
    53.             spawnerDoneGameObject.SetActive(true);
    54.         }
    55.     }
    56. }
    57.  
     
    Last edited: Nov 12, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

    http://plbm.com/?p=236

    Steps to success:
    - find which collection it is (critical first step!)
    - find out why it has fewer items than you expect
    - fix whatever logic is making the indexing value exceed the collection
    - remember you might have more than one instance of this script in your scene/prefab

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    You may edit your post above.