Search code examples
c#unity-game-enginelerp

Unity awaitForSeconds called before lerp animation ends


I have created a simple lerp animation that moves an object from one place to the other using this code:

public IEnumerator Move(Vector3 position, Transform transform, float animationTime = 1)
{
float timePassed = 0;
transform.position = Vector3.Lerp(startPos, position, timePassed /animationTime);
timePassed += Time.deltaTime;
yield return null;
}

and I call it from another script. But I want it to do something after the animation. if I create a Coroutine and use yield return WaitForSeconds(animationTime); the Coroutine ends before the animation and it causes bugs.

I have also tried to create variable that count the time passed (like in the animation) but for no avail…

What am I doing wrong ¿

EDIT: I can't change the Move function because it is used in other classes and I want to make it as generic as possible


Solution

  • You can use a coroutine and loop every frame, and after the loop is done you can just trigger a callback. A quick example can be:

    public IEnumerator Move(Vector3 position, Transform transform, float animationTime = 1, Action callback = null)
    {
        float lerp = 0;
        do
        {
            lerp += Time.deltaTime / animationTime;
            transform.position = Vector3.Lerp(startPos, position, lerp);
            yield return null; // wait for the end of frame
        } while (lerp < 1);
    
        if (callback != null)
            callback();
    }
    

    P.S.: I didn't test this code in editor. It may have any typo.