Repeating countdown timer that displays to text

I think my brain is broken, I feel like this should be easy but I cannot get it right. How do I correct this so that it repeats again every 30 seconds?

I am trying to use a Coroutine to create and repeating countdown timer of 30 seconds. Every 30 seconds it should call an event and then repeat the timer for another 30 seconds, over and over again. It should also display the countdown to the UI.

I am avoiding Update() because I had performance issues.

    [SerializeField] private float timeToSpawn = 30f;
    [SerializeField] private TMP_Text spawnTimerDisplay;
    public static event Action Spawn;

    private void Start()
    {
        {StartCoroutine(SpawnTimer(timeToSpawn));}
    }

    private IEnumerator SpawnTimer(float t)
    {
        float spawnTimer = 0;

        while(spawnTimer <= t)
        {
            spawnTimer += Time.deltaTime;

            DisplayTime(spawnTimer);

            if(spawnTimer == 0)
            {
                Spawn?.Invoke();
            }

            yield return null;
        }
    }

    void DisplayTime(float timeToDisplay)
    {
        timeToDisplay += 1;
        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);
        spawnTimerDisplay.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }

Cooldown timers, gun bullet intervals, shot spacing, rate of fire:

https://discussions.unity.com/t/821482/2

GunHeat (gunheat) spawning shooting rate of fire:

https://discussions.unity.com/t/824570/2

As for this:

Never test floating point (float) quantities for equality / inequality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

https://discussions.unity.com/t/851400/4

https://discussions.unity.com/t/843503/4

“Think of [floating point] as JPEG of numbers.” - orionsyndrome on the Unity3D Forums

1 Like

Thank you Kurt-Dekker, I appreciate response. I will remove the test for float, but how would you invoke the Event in this case?

Also I noticed all these links refer to Update() function, is that not inefficient compared to fixing this as a Coroutine?

I have also considered separating the two, the Event can easily be called in a basic WaitForSeconds(30f). And then have the timer be separate; but if I can get it in one single method it may sync better.

Unfortunately there’s a lot of nonsense like this posted all over the web.

All scripting stuff runs in one thread.

Here is some timing diagram help:

https://docs.unity3d.com/Manual/ExecutionOrder.html

What do you mean “sync?”

Everything happens one thing at a time in Unity and nobody can see ANYTHING until the frame is rendered and presented (see timing diagram above).

Very short timers… there’s just no need:

https://discussions.unity.com/t/886711/6