【问题标题】:Unity awaitForSeconds called before lerp animation ends在 lerp 动画结束之前调用 Unity waitForSeconds
【发布时间】:2019-08-15 11:33:58
【问题描述】:

我创建了一个简单的 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 函数,因为它在其他类中使用,我想让它尽可能通用

【问题讨论】:

  • 你的方法 Movevoid 类型而不是 IEnumerator 类型,所以现在这个方法不被认为是统一的协程
  • 哦,我的错,我是用手机写的,所以很难检查。我现在就修复它

标签: c# unity3d lerp


【解决方案1】:

与动画“同时”运行的协程?听起来它很容易在不同的fps上中断。

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

【讨论】:

  • 我写的动画是通过代码完成的,而不是动画文件
【解决方案2】:

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

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

【讨论】:

  • 我会给这个机会
  • 它就像一个魅力,但我仍然不明白为什么协程没有按预期工作
【解决方案3】:

你可以把它放在协程中:

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

【讨论】:

    【解决方案4】:

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

    void Move(Vector3 position, Transform 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);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 2018-11-30
      • 2016-08-13
      • 2016-11-26
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多