I want to execute coroutine 1 time per second, but in practice it turns out that when the program is started, it is waiting for a second, then the coroutine execute without delay.
void Update() {
StartCoroutine("DecreaseParameters");
}
IEnumerator DecreaseParameters() {
yield return new WaitForSeconds (1);
CurrentHunger -= 1;
}
Can’t understand, what’s wrong.
gheeler
February 11, 2015, 10:06am
2
you’re calling startcoroutine every frame.
so each call is still waiting for a second before it reduces currentHunger.
This will do it. Could easily be taken out into it’s own method.
float hungerTimer=0;
void Update()
{
if (hungerTimer >= 1)
{
currentHunger -= 1;
hungerTimer = 0;
}
hungerTimer += Time.DeltaTime;
}
InvokeRepeating() is a better way to execute code after timed intervals.
Doc: Unity - Scripting API: MonoBehaviour.InvokeRepeating