Loop with delay

I’m fairly new to Unity and I was trying to create a primitive city simulation with a population counter that would update its text component every two seconds.

I’ve tried Coroutines and InvokeRepeating but none of them seemed to work as I wanted to (there was a 2 second delay at first but after that the text component updated every frame).

Attempt I.

void Update()
    {
        StartCoroutine(DisplayPopulation());
    }

    IEnumerator DisplayPopulation()
    {
        populationText.text = population.ToString();
        population += 100;
        yield return new WaitForSeconds(2);
    }

Attempt II.

void Update()
    {
        StartCoroutine(DisplayPopulation());
    }

    IEnumerator DisplayPopulation()
    {
        while (true)
        {
            populationText.text = population.ToString();
            population += 100;
            yield return new WaitForSeconds(2);
        }
    }

Attempt III.

void Update()
    {
        InvokeRepeating("PopulationCount", 2f, 2f);
    }

    void PopulationCount()
    {
        populationText.text = population.ToString();
        population += 100;
    }

I’ve probably just understood these poorly and I apologise for that but I’ve been unable to find a proper solution for this (or at least one that I would be able to understand).

Thanks in advance for any help or advice!

Attempt 1 would just wait a couple of seconds before ending the coroutine, however, you are starting a new routine every frame.

Attempt 2 would work if you started the routine just once, say in the Start(). You are currently starting a new routine every frame in Update() just as with 1.

Attempt 3 has the same problem again. You are setting an instruction to invoke the method every frame. Do it just once in Awake() or Start() and it will work.

1 Like

Moved the Coroutine to the Start() and it works as it should, thanks! :slight_smile:

Start() can be a coroutine, so you could just do this is you like;

private WaitForSeconds _waitTwoSecs = new WaitForSeconds(2);

private IEnumerator Start()
{
    while (true)
    {
        populationText.text = population.ToString();
        population += 100;
        yield return _waitTwoSecs;
    }
}
1 Like