Question by
cowbears101 · Jun 12, 2018 at 09:19 PM ·
c#arrayindexoutofrangeexception
Index Out Of Range Exception When Spawning Second Wave
I've been working on a wave spawner for me Unity game, that allows me to choose a specific enemy prefab, and give it a time to start spawning, and at what rate to spawn. The only issue is, when I get to the second wave, I get an 'Array Index Out Of Range' error, yet I haven't been able to figure out the exact issue, but I know that the error appears when I try to set the 'enemies' variable to have the value 'wave.Enemies[enemyIndex];':
IEnumerator SpawnWave()
{
Wave wave = waves[waveIndex];
Wave.EnemiesToSpawn enemies;
EnemiesAlive = wave.totalCount;
for (int i = 0; i < wave.groupNum; i++)
{
enemies = wave.Enemies[enemyIndex];
for (int j = 0; j < enemies.count; j++)
{
SpawnEnemy(enemies.enemy);
yield return new WaitForSeconds(1.0f / enemies.rate);
}
enemyIndex++;
}
waveIndex++;
}
By default, the enemyIndex and waveIndex variables have a value of 0. This is what the 'Wave' class looks like. I have it stored in a separate script file:
using UnityEngine;
[System.Serializable]
public class Wave {
[System.Serializable]
public class EnemiesToSpawn
{
public GameObject enemy;
public int count;
public float delayToSpawn;
public float rate;
}
public EnemiesToSpawn[] Enemies;
[Header("Manual Values")]
public int groupNum;
public int totalCount;
}
Also, this is my exact error, for anyone who wants it.
IndexOutOfRangeexception: array index is out of range.
WaveSpawner+<SpawnWave>c_Iterator0.Movenext() (at Assets/Scripts/WaveSpawner.cs:67)
I am also currently running Unity 5.6.5f, and the above code is in c#.
Comment