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);
}