Wait for an animation to finish in unity3d

2020-03-31 04:36发布

问题:

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.

My code:

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

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?

回答1:

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

  1. Start the animation.
  2. Wait for the animation to finish before you play next animation.

An example of how this could be done is:

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

And the definition for WaitForAnimation would be:

C#:

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

JS:

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

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

Source, alternatives and discussion.