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

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.

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