等待动画在unity3d中完成

Wait for an animation to finish in unity3d(等待动画在unity3d中完成)

本文介绍了等待动画在unity3d中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Update 函数中播放的动画,在 Switch 的情况下.

I have an animation which plays in the Update-function, in a Switch case.

动画结束后,布尔值被设置为真.

After the animation finishes, a Boolean is being set to true.

我的代码:

case "play":    
    animation.Play("play");     
    gobool = true;
    startbool = false;
    break;

问题是我的 goboolstartbool 在没有完成动画的情况下立即设置.如何让我的程序等到动画完成?

The problem is my gobool and startbool get set immediately without finishing the animation. How can I let my program wait untill the animation is finished?

推荐答案

基本上你需要做两件事才能让这个解决方案发挥作用:

Basically you need to do two things for this solution to work:

  1. 开始动画.
  2. 等待动画完成,然后再播放下一个动画.

如何做到这一点的一个例子是:

An example of how this could be done is:

animation.PlayQueued("Something");
yield WaitForAnimation(animation);

WaitForAnimation 的定义是:

C#:

private IEnumerator WaitForAnimation (Animation animation)
{
    do
    {
        yield return null;
    } while (animation.isPlaying);
}

JS:

function WaitForAnimation (Animation animation)
{
    yield; while ( animation.isPlaying ) yield;
}

do-while 循环来自实验表明 animation.isPlaying 在调用 PlayQueued 的同一帧中返回 false.

The do-while loop came from experiments that showed that the animation.isPlaying returns false in the same frame PlayQueued is called.

稍加修改,您就可以为动画创建一个扩展方法来简化此操作,例如:

With a little tinkering you can create a extension method for animation that simplifies this such as:

public static class AnimationExtensions
{
    public static IEnumerator WhilePlaying( this Animation animation )
    {
        do
        {
            yield return null;
        } while ( animation.isPlaying );
    }

    public static IEnumerator WhilePlaying( this Animation animation,
    string animationName )
    {
        animation.PlayQueued(animationName);
        yield return animation.WhilePlaying();
    }
}

最后你可以轻松地在代码中使用它:

Finally you can easily use this in code:

IEnumerator Start()
{
    yield return animation.WhilePlaying("Something");
}

来源、替代方案和讨论.

这篇关于等待动画在unity3d中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:等待动画在unity3d中完成