Coroutine code running faster in build.

I am having some issues animating an object through a coroutine.

The code is running faster in the build causing the movement to go faster than in the editor.

IEnumerator RunAnim()
{
    Vector3 location = transform.position + (Vector3)Random.insideUnitCircle * 1f;
    float t = 0;
    while (transform.position != location)
    {
        float p = t / animTime;
        transform.position = Vector3.Lerp(transform.position, location, p);
        t += Time.deltaTime;
        yield return 0f;
    }
}

I don’t see any reason as to why it would run faster. It is based on animTime which is set to 1 right now and works as intended in the editor, but when I build the game and run it. The animation happens in the blink of an eye.

Does this change anything for ya?

IEnumerator RunAnim()
{
    Vector3 location = transform.position + (Vector3)Random.insideUnitCircle * 1f;
    float t = 0;
    Vector3 startpos = transform.position;
    for( ; t <= animTime; t += Time.deltaTime) {
        float p = t / animTime;
        transform.position = Vector3.Lerp(startpos, location, p);
        yield return null;
    }
    transform.position = location;
}

The math in the Lerp is messed-up. There are two common movement Lerp-uses, but that line is a mash of both.

Version 1 looks like “current=Lerp(savedStart, end, increasingFrom0to1Num)”. It gives a constant movement, frame rate independent. Version 2 doesn’t save the start, it’s: “current=Lerp(current, end, fixedSmallNumLike0.1)”. It gives a fast-then-slow move and isn’t frame rate independent (but is close enough.)

A longer explanation/examples is in the vector movement chapter at taxesforcatses-dot-com, or you can just google Unity Lerp and notice those two ways of using it.

2 Likes

Damn should have seen that earlier. Was using Vector3.MoveTowards so when I changed it over to use lerp as it was more what I wanted, I forgot to setup the lerp properly.

Just so everyone who is experiencing this all I needed to change was the lerp to use a cached start position for the animation. It also solved some other problems I was having with other parts of the animation(took most of the code out to do some testing.)

Glad you got it resolved :slight_smile: