- Home /
How to prevent infinite loop when Array Index Is Out Of Range
Basically, my problem is that I'm using variable "i" to flip through an array of spawn points. When i becomes greater than the amount of spawn points available, "i" obviously leaves the range of the spawn point array. My solution is to simply reset "i" inside the scope of the for loop, but this doesn't seem to solve my problem. What's going on?
function spawnWave()
{
if(waveActive)
{
for (var i=0; i<=waveNumber; i++)
{
if (i>8)
{
i = 0;
print(i);
}
Instantiate(enemy1, Vector3(spawnArray[i].transform.position.x, spawnArray[i].transform.position.y, spawnArray[i].transform.position.z), Quaternion.identity);
//something to delay spawning for more than six
}
waveActive = false;
needSpawn = false;
}
else
{
yield WaitForSeconds(1);
waveActive = true;
}
}
Answer by moghes · May 05, 2012 at 08:04 AM
you can use Invoke("callYourFunction", 3) for example, it will call the function in 2 seconds. In your case you can change the value of waveActive = true; inside a function and call the function from Invoke, hope it helps!
Answer by aldonaletto · May 05, 2012 at 12:46 AM
If you want to iterate through all elements of spawnArray, it's easier to do the following:
for (var spawnPt in spawnArray){
Instantiate(enemy1, spawnPt.transform.position, Quaternion.identity);
}
But if you need the index, use the array length in a regular for loop:
for (var i=0; i < spawnArray.length; i++){
Instantiate(enemy1, spawnArray[i].transform.position, Quaternion.identity);
}
Anyway, you don't need to create a new Vector3 with the position values - position itself is a Vector3, thus you can use it directly.
hmmm....out of curiousity, is there a way to have it step through the array slower? I've tried "WaitForSeconds(3)" for instance, but it doesn't seem to do anything. Adding "yield" seems to create another infinite loop. Think you can help me out again? And thanks for answering my previous question!
It's easy in JS:
for (var i=0; i < spawnArray.length; i++){ Instantiate(enemy1, spawnArray[i].transform.position, Quaternion.identity); yield WaitForSeconds(3.0); }But you must understand how coroutines work: when you call a coroutine, it starts running and returns to the caller when the first yield is encountered - but continues running in the background, being resumed automatically each frame until its completion. You should thus make sure to not call the coroutine again until it ends, or multiple coroutine instances will run at the same time, crowding your level with tons of enemies.
A common approach is to use a boolean flag set at the coroutine start and cleared upon return:
private var spawning = false;
function spawnWave(){ if (spawning) return; // abort calls while spawnWave is running spawning = true; // set flag "spawnWave is running" if (waveActive){ ... } else { ... } spawning = false; // clear flag right before returning }