Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any ways to make coroutines fps independent?

I am using a coroutine to animate the fading effect on my objects material.

public IEnumerator DissolveIn()
{
    float elapsed = 0f;
    while (elapsed < 1)
    {
        elapsed += Time.deltaTime;
        for (int i = 0; i < 7; i++)
        {
            Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
            float fade = math.lerp(mat.GetFloat("_Fade"), .8f, .22f);
            mat.SetFloat("_Fade", fade);
        }
        yield return null;
    }
    for (int i = 0; i < 7; i++)
    {
        Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
        mat.SetFloat("_Fade", 1f);
    }
}

The problem is the speed of the animation is changing with the fps changes. If someone plays the game with 30 fps the animation becomes slow. And for someone with 200 fps it is too fast to even see what is happening.

Is there any way for me to make this fps independent?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use delta time, but compute elapsed based on the animation’s start time and the current time, something like this. You can also get rid of the final for loop by doing it within the animation loop:

public IEnumerator DissolveIn()
{
    float startTime = Time.time;
    while (true)
    {
        float elapsed = Math.min(1, Time.time - startTime);

        for (int i = 0; i < 7; i++)
        {
            Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
            float fade = math.lerp(mat.GetFloat("_Fade"), .8f, .22f);
            mat.SetFloat("_Fade", fade);
        }
        if (elapsed >= 1)
            break;
        yield return null;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading