I wanted to make a countdown timer using a coroutine, but for some reason something goes wrong when the coroutine is running.
I have a TimeManager class which does the counting.
using UnityEngine;
using System.Collections;
public class TimeManager : MonoBehaviour
{
public static TimeManager use;
int count = 30;
public int Count
{
get
{
return count;
}
}
void Awake()
{
if (use != null)
GameObject.Destroy(use);
else
use = this;
DontDestroyOnLoad(this);
}
public void SetTimer(int seconds)
{
count = seconds;
}
public void StartTimer()
{
StartCoroutine(Countdown());
}
IEnumerator Countdown()
{
while (count >= 0)
{
yield return new WaitForSeconds(1f);
count--;
Debug.Log(count);
}
}
}
And then I start the counter from my StartLevel script
using UnityEngine;
using System.Collections;
public class StartLevel : MonoBehaviour
{
void Start ()
{
TimeManager.use.SetTimer(120);
TimeManager.use.StartTimer();
}
}
The debug output from the TimeManager always shows 2 ticks per second. So it shows
119
118
<Wait a second>
117
116
<Wait a second>
115
114
<And so on...>
and I don’t understand why.
Any idea as to why it decrements count twice every time?