(Fixed / Answered) - Regarding IEnumerator

Hey guys, I’m trying to use IEnumerator so I can get certain scripts / functions to wait before executing, and I really don’t understand why this is being such a pain. It’s so simple in UnityScript and then just seems stupidly overcomplex in C#…

Would love some help or explanation on this…

void Update ()
    {
        if(playerInZone == true && canSpawn == true)
        {
            StartCoroutine("SpawnZombie");
        }
    }

    IEnumerator SpawnZombie()
    {
        Debug.Log ("Waiting 15 seconds....");
        yield return new WaitForSeconds (15);
        int temp;
        temp = Random.Range(0, spawnSpots.Count);
        Instantiate(ZombiePrefab, spawnSpots[temp].transform.position, spawnSpots[temp].transform.rotation);
        zombieCount ++;
        Debug.Log ("Spawning a zombie now");
    }

These is my code, what i’m trying to make it do is, if the player is in a certain zone and they are allowed to spawn, then every 15 seconds (for example), choose a random spawn location (working fine) and spawn 1 of them.

But at the minute it waits the seconds at the start and then spawns up to the max zombie’s or waaaaay above without waiting for the seconds… Any idea’s?

because the StartCoroutine is in the Update function, it is starting the coroutine every frame.
You need to stop calling StartCoroutine after the first time. eg:
bool spawning = false;
if(playerInZone == true && canSpawn == true && spawning == false)…
spawning = true

1 Like

Because you’re calling it in your Update method.

What you can do is have a canSpawn flag, coroutine that tracks the cooldown, and a spawn function. Something like this…

IEnumerator StartCooldownTimer()
{
    canSpawn = false;
    yield return new WaitForSeconds(15f);
    canSpawn = true;
}

void AttemptSpawn()
{
    if(!canSpawn)
        return;
    StartCoroutine(StartCooldownTimer());

    // put spawn code here
}

void Update()
{
    if(playerInZone == true && canSpawn == true)
        AttemptSpawn();
}

Or if thats your use case just use InvokeRepeating

Okay thank you all for your replies.
It makes sense now :slight_smile:
And thank you @JohnnyA , I never knew about Invoke Repeating, so I’ll give it a shot :slight_smile:

// Closed (unless there is a way to actually close a thread? :slight_smile: )