unity awaitForSeconds 在lerp动画结束前调用

Unity awaitForSeconds called before lerp animation ends

我创建了一个简单的 lerp 动画,它使用以下代码将对象从一个地方移动到另一个地方:

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;
}

我从另一个脚本调用它。 但我希望它在动画之后做一些事情。如果我创建一个 Coroutine 并使用 yield return WaitForSeconds(animationTime); Coroutine 在动画之前结束,这会导致错误。

我也曾尝试创建变量来计算经过的时间(就像在动画中一样)但无济于事……

我做错了什么 ¿

编辑: 我无法更改 Move 函数,因为它在其他 类 中使用,我想让它尽可能通用

作为动画运行 "same time" 的协程?听起来它很容易在不同的 fps 上崩溃。

我强烈建议您在最后一个关键帧上使用 AnimationEvent。只需在动画中创建一个 public 方法和关键帧事件,然后 select 该方法。它会在最后调用。

你可以使用协程,每帧循环,循环完成后触发回调即可。一个简单的例子可以是:

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.: 我没有在编辑器中测试这段代码。可能有错别字。

你可以把它放在协程中:

float timePassed=0.0f;
while(timePassed<=animationTime)
{
 transform.position = Vector3.Lerp(startPos, position, timePassed /animationTime);
 timePassed += Time.deltaTime;
 yield return null;
}
//all the stuff you want to do after the animation ended

您可以尝试在协程完成后使用它发回 return 值:

void Move(Vector3位置,Transform变换,float animationTime = 1) {

StartCoroutine(DoMove(position, transform, (moveIsDone) => {if(moveIsDone) { ... };});


IEnumerator DoMove(Vector3 position, Transform transform, float animationTime, System.Action<bool> callback)
{

    float timer = 0f;
    while(timer < 1f)
    {
        timer += Time.deltaTime / animationTime;
        transform.position = Vector3.Lerp(startPos, position, timer);
        yield return null;
    }
    callback(true);

}