Coroutine is called twice less time than update
Hello guys! Im trying to adjust filler based on time like this
https://docs.unity3d.com/ScriptReference/UI.Image-fillAmount.html
void Update ()
{
//Reduce fill amount over 30 seconds
cooldown.fillAmount -= 1.0f/30* Time.deltaTime;
}
Its very simple, in update it works perfectly, but i need to call this in a coroutine like this:
void Update() {
Debug.Log("update");
if (!phaseControlIsRunning)
StartCoroutine (BattlePhaseControl());
}
IEnumerator BattlePhaseControl()
{
phaseControlIsRunning= true;
monsterInfo.PrepareTime/ * Time.deltaTime;
yield return new WaitForSeconds(0);
phaseControlIsRunning = false;
Debug.Log("coroutine");
}
Now i need to divide PrepareTime by 2, because coroutine is called twice time less than update like this. If i dont do this, 5 seconds will be like 10, 20 like 40 etc. I know its easy to divide by 2, but can anyone explain why is that? This is my log:
Is that your actual code? The following line should have generated a compile error:
monsterInfo.PrepareTime/ * Time.deltaTime;
Going by your code it makes sense for "update" to be logged to the console more than "coroutine". At first the console will log "update". Then you start the Coroutine, and "Wait" for 0 seconds, which pretty much just waits for the next frame. When the next frame starts, Update is called again, the Coroutine is NOT restarted because of phaseControlIsRunning , and then the console logs "coroutine". Next frame, it logs "update" again, the coroutine will start again and the whole things keeps going and going, with "update" being called 2 times more than "coroutine".
Answer by Pengocat · Jan 19, 2017 at 06:10 PM
Whenever a Coroutine "yield" it waits for update or whatever condition to be met before it runs again. If you add a log in the beginning of the Coroutine you will notice that everything before yield is done in the first update and the last bit in the second update. yield return null
is much better to use thanyield return new WaitForSeconds(0)
.