简体   繁体   中英

Wait for an animation to finish in unity3d

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM