- Home /
Why is my Mathf.Movetowards Coroutine executing instantly?
public IEnumerator ChangeFogDensity (float targetDensity, float speed = 1.0f)
{
while (RenderSettings.fogDensity != targetDensity)
{
RenderSettings.fogDensity = Mathf.MoveTowards(RenderSettings.fogDensity, targetDensity, speed * Time.deltaTime);
Debug.Log("Fog Density is" + RenderSettings.fogDensity);
yield return null;
}
Debug.Log("Fog density changed.");
}
This should gradually fade the fogDensity towards targetDensity over time, but instead it's happening instantly when called with StartCoroutine. Can anybody figure out the dumb thing I'm doing wrong?
--Rev
What do the logs show? If the first logging line only gets written once, then it suggests that the values are such that a single "move towards" takes it all the way there.
I would start by adding a logging line on entry to the function, showing the values of RenderSetitngs.fogDensity, targetDensity, and speed at that point.
Are you sure you're calling this method through the StartCoroutine method?
Answer by Reverend-Speed · Nov 23, 2019 at 01:23 AM
Hey folks, just cleaning up some hanging Questions on my account. Here's the code that was used in the final product:
public IEnumerator ChangeFogDensity (float targetDensity, float timeInSeconds = 1.0f)
{
float startingValue = RenderSettings.fogDensity;
for (float t = 0; t < 1.0f; t += Time.deltaTime / timeInSeconds)
{
RenderSettings.fogDensity = Mathf.Lerp(startingValue, targetDensity, t);
yield return null;
}
}
Hope this is of some use.
Answer by Pangamini · Aug 28, 2019 at 02:22 PM
Your enumerator / coroutine yields null in the loop - it means the next iteration is executed immediately. You need to yield some YieldInstruction, such as new WaitForSeconds, to tell the engine it should execute the next iteration in some later frame
you could write yield return new WaitForSeconds(0)
to continue in the next frame. But that allocates a new WaitForSeconds object every frame, generating unnecessary garbage. So you could just allocate it once before the loop, storing in a coroutine's local variable. But I usually have one instance of WaitForSeconds(0) stored in a global variable
Yes that's what I thought at first too - that yield null should continue in the next frame. Has this behavior changed? Does it depend on when was the coroutine started, perhaps?
No, it's not changed, and I'm curious as to how you got to thinking this way.
I'm not even sure if I understand what you meant; if the next iteration were "executed immediately" then the yield return null
line would have no effect whatsoever, right..?