Wait for an animation to finish in unity3d

后端 未结 1 864
無奈伤痛
無奈伤痛 2021-01-16 08:33

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.

相关标签:
1条回答
  • 2021-01-16 08:53

    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.

    0 讨论(0)
提交回复
热议问题