Adding A delay to enemy respawn

I found a very simple way to add a delay time to the enemy respawn time. Use it how you please!

This gets added to the Update() method. The reason for the StartCoroutine is so that no other code is executed while the delay is happening.

if(allEnemiesDead()) {
        Debug.Log("END!");

        // Create dely before new enemys are spawned
        StartCoroutine(delay(2));
    }

Here is the method for the delay. You have to add the bool variable ‘isCoroutineExecuting’ otherwise new enemy ships will continuously respawn inside the Coroutine for the length of your ‘time.’ I believe this is because the method call happens inside the Update() method. You obviously have to create a ‘isCoroutineExecuting’ variable with your other global variables (I’ll let you figure out what bit to set it to).

IEnumerator delay(float time) {
    if (isCoroutineExecuting)
        yield break;
    isCoroutineExecuting = true;
    yield return new WaitForSeconds(time);
    // Code to execute after the delay
    spawnEnemys();
    isCoroutineExecuting = false;

}
1 Like

Can’t you just use the Invoke features built into Unity. So something like:

if(allEnemiesDead()) { Invoke("spawnEnemys", 2); }

Thanks,

Am going to try this and let you know how did it went :slight_smile: