How can I wait for an animation to complete?

I have a piece of code that want to wait for an animation to complete.

I realize I can try to time the event with Invoke or WaitForSeconds, but since the animation can vary in length I don't find this method that appealing.

I'd like there to be a WaitForAnimation yield instruction so I can easily play code in sequence.

Something like:

// Warning: Code does not work. 
//          Don't use in your project.
function Start()
{
    yield WaitForAnimation( animation.PlayQueued( "Intro" ) );
    Debug.Log("Animation is complete");
}

or even shorter like

// Warning: Code does not work. 
//          Don't use in your project.
function Start()
{
    yield animation.PlayQueued( "Intro" );
    Debug.Log("Animation is complete");
}

Are there nice options to synchronize animation completion? (Is there a global list of methods that work with coroutines?)

14 Answers

14

Here is a solution I came up with that waits for the animation to finish. It doesn't work too well in case you have multiple animations queued up from any other source, but as long as you're calling the animations from one single place, this works.

Basically you need to do two things for this solution to wotk;

  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 follows:

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 experimentation that the animation.isPlaying return false the same frame you call PlayQueued for some reason.

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

You need to call yield return StartCoroutine(WhilePlaying(ballGroupAnimation, "open"));

Even though it’s older, this Q&A tends to rise to the top in searches. But fortunately, I dug deeper before going to work. This solution may not have been available with previous builds, but nowadays, you can use the built-in animation events system.

Thanks for the pointer, I don't have enough repto upvote sadly.

I wasn't able to find how to use this with the legacy system, but see also http://docs.unity3d.com/Documentation/ScriptReference/AnimationClip.AddEvent.html

This should now be referred as the best answer !

This is a terrible idea - animation events will not fire if a frame is skipped, making them unreliable. Vote this down.

That link to the built-in animation events system is 404. Maybe this one? https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html

   function Update() {
        if (!animation.IsPlaying("YourAnimation"))
            print("Animation Done");
    }

Actually, when I run that code (except that my animation reference is on another object), it reports Animation Done the first frame it runs. Then it doesn't say anything for a while, and after it is done spams out Animation Done. Also, it doesn't really help since I want to play code in sequence, so that I can play one animation, then do something else, then play another animation, then do something else etc.

Ok, I guess the first time printing "done" is because your this code is run before you animation starts. To apply this to your case you need to know which interactions happen to trigger an animation or check whether is stopped playing. If you clarify more I can help you write the code.

I start the animation in Start. It appears that the animation.IsPlaying returns false during the same frame.

You could try checking to see when the current time of your animation is larger than the length of the animation. The docs say that the animation time goes to infinity because it loops the animation over and over. I am assuming that animation time stops when you pause an animtion. I have not tested this but it would go something like:

while (AnimationState.time >= AnimationState.length)
{
    yield return null;
}
return bAnimFinished;

or the non-coroutine way

if (AnimationState.time >= AnimationState.length)
{
    // animation finished...
}

The problem is an animation may be stopped at an arbitrary point in time. Relying on the duration instead of check it's actually playing doesn't cover this scenario. Trying to add extra support to handle the case quickly lead to messy code. If you are absolutely certain no other code will interfere with method, it's clean way of waiting for it with minimal code. A flaw in the current AA is however that another animation might be started so the coroutine waits for the second animation to complete.

if (AnimationState.time >= AnimationState.length) :)

Now that's something! Thanks a ton I will consider trying this out tonight. Put it in an answer and I'll vote it up.

added comment in answer form!

A more general solution is to set up a notification at some arbitrary time in the animation cycle, where the end of the cycle is a special case. I’ve created a class that holds an animation clip, and fires an event at a specified time in the animation cycle. I will present two equivalent implementations below, one that uses class AnimationEvent (which is sort of the native Unity way), and one that uses a Coroutine to measure the animation time against the notification time.

Personally, I prefer using the second technique. Why? Unity uses its messaging system (e.g. SendMessage()) to fire the AnimationEvent. The message is bound only by the name of the method, and the message is sent to all script components on the GameObject. If some other script on your GameObject has a method with the same name, it too will receive the message, which is almost certainly a bug.

You can mitigate the issue by creating a mangled name for your method, but that gets really ugly–and it doesn’t even completely solve the problem! Consider if you have two instances of the script component on a single GameObject. (You might do this if you have two different clips that you want to monitor.) Now both components receive the message, regardless of the method name. I’ve addressed this by adding the script’s object ID as a parameter on the AnimationEvent, and then checking the value in the message handler. It works, but it does add complexity.

As for sending the notification to the outside world, you could use SendMessage(), but I prefer using a .NET event. It has several advantages: you get better performance; you avoid the binding issue described above; it is architecturally more elegant, as it insulates the class from being concerned with who’s listening for the notification.

So, the prose are nearly complete. :slight_smile: To use this, add it as a component to the GameObject that gets animated. You can set the clip at design time or at run-time. I’ve expressed the time to fire the notification as animation frames, but you could just as well use seconds; if the frame is set to zero, I take that to mean at the end of the clip. You attach a handler to the NotifyFrameReached event, and voila! You have notification that you’ve reached the specified frame!

CAVEATS:

  • In the Message-based implementation, I don’t provide means to remove the AnimationEvent; if you were to set a second clip at run-time, the event on the old clip would continue to fire each time it runs.
  • When you add a handler to a .NET event, you should make sure to remove it once you no longer need to handle the event; else you will leak memory.

And without further ado, my preferred Coroutine-based implementation:

using UnityEngine;

using System;

using System.Collections;

public class NotifyingAnimControl_CoroutineBased : MonoBehaviour

{

//--------------------------------------------------------------------------
public float  notificationFrame;

//--------------------------------------------------------------------------
[SerializeField]
AnimationClip animClip;

//--------------------------------------------------------------------------
public event EventHandler NotifyFrameReached;

//--------------------------------------------------------------------------
protected void RaiseNotifyFrameReached()
{
    var handler = NotifyFrameReached;

    if( null == handler ) return;

    handler( this, EventArgs.Empty );
}

//--------------------------------------------------------------------------
public void SetClip( AnimationClip clip )
{
    animClip = clip;

	// Note--you can have different wrap modes if you want...
    animClip.wrapMode = WrapMode.Once;

    ScheduleNotification();
}

//--------------------------------------------------------------------------
public void PlayAnimation()
{
    animation.CrossFade( animClip.name );

    // NOTE: It is critical to start this *after* starting the clip, else
    // the CheckEventTime fails on it's first iteration!
    StartCoroutine( CheckEventTime() );
}

//--------------------------------------------------------------------------
void Start()
{
    if( null != animClip )
    {
        SetClip( animClip );
    }
}

//--------------------------------------------------------------------------
float EventTime { get; set; }

//--------------------------------------------------------------------------
AnimationState AnimState { get { return animation[ animClip.name ]; } }

//--------------------------------------------------------------------------
protected void ScheduleNotification()
{
    EventTime = (0 == notificationFrame)
              ? animClip.length
              : notificationFrame / animClip.frameRate;
}

//--------------------------------------------------------------------------
// The virtue of using this technique (rather than an AnimationEvent) is
// that AnimationEvent fires its signal using SendMessage(), which winds
// up going to all components on the GameObject.  If the GameObject has
// more than one of these components on it, they *all* receive the message.
// You then need a filter to figure out if the component is the intended
// receiver, and in the mean time, you are getting superfluous events.
IEnumerator CheckEventTime()
{
    while( AnimState.time < EventTime  &&
           animation.IsPlaying( animClip.name ) )
    {
        yield return new WaitForEndOfFrame();
    }

    RaiseNotifyFrameReached();
}

}

And here’s the Messaged-based implementation:

using UnityEngine;
using System;

public class NotifiyingAnimControl_MessageBased : MonoBehaviour

{

   //--------------------------------------------------------------------------
public float notificationFrame;

//--------------------------------------------------------------------------
    [SerializeField]
AnimationClip animClip;

//--------------------------------------------------------------------------
public event EventHandler NotifyFrameReached;

//--------------------------------------------------------------------------
protected void RaiseNotifyFrameReached()
{
	var eventDelegate = NotifyFrameReached;
	if( null == eventDelegate ) return;
	
	eventDelegate( this, EventArgs.Empty );
}

//--------------------------------------------------------------------------
public void SetClip( AnimationClip clip )
{
    animClip = clip;

	// Note--you can have different wrap modes if you want...
    animClip.wrapMode = WrapMode.Once;

    ScheduleNotification();
}

//--------------------------------------------------------------------------
void Start()
{
    if( null != animClip )
    {
        SetClip( animClip );
    }
}

//--------------------------------------------------------------------------
protected void ScheduleNotification()
{
	var animEvent = new AnimationEvent();

            animEvent.time = (0 == notificationFrame)
                                     ? animClip.length
                                     : notificationFrame / animClip.frameRate;

	animEvent.functionName = "DoGenericOneShotNotification";
	animEvent.intParameter = GetInstanceID();
	
	animClip.AddEvent( animEvent );
}

//--------------------------------------------------------------------------
public void PlayAnimation()
{
	animation.CrossFade( animClip.name );
}

//--------------------------------------------------------------------------
void DoGenericOneShotNotification(AnimationEvent animEvent)
{
            if( animEvent.intParameter != GetInstanceID() ) return;
	
	RaiseNotifyFrameReached();
}

}

If that works - great, but what Unity needs is a built-in function 'IsComplete' or something similar. I've spent a day digging into this issue - a day that means I might not meet a deadline - and there's many threads with arcane solutions to this problem. Most of them don't work. At this point, I regret using Unity and am considering a switch to Unreal.

I’m not crazy about any of the other answers for a couple reasons:

  • IsPlaying() seems to require you to set the wrap mode to Once - and once the animation is at its end the character snaps to their default pose - it’s too late to do a CrossFade. So your animations would have to be perfectly matched to look good.
  • if you use one of the Length or Time options, what if you want to play the animation at a different speed?

My favorite looks like this - it uses normalizedTime, which goes from 0 to 1, with 0 being the start and 1 being the end of the animation:

	bool AnimationStillPlaying( string animationName )
	{
		return _animation.IsPlaying(animationName) && _animation[animationName].normalizedTime<1.0f;
	}

And I generally try to avoid coroutines - they seem like a recipe for state bugs - but if you want to use one you could easily merge this answer with one of the others.

Waiting for animation to finish playing is bad practice. There should simply be an ‘onComplete’ function for animations so we can trigger game logic deterministically.

sorry if i'm late to the party but could you put a boolean in which returns true when your animation is playing and returns false once it stops? Whilst that is true cue any other animations then once it's returned false play 1st cued animation etc.

Sorry if this misses the point, i had a look at your fix but don't understand the C languages too well (at all if I'm honest)

If I understood you correctly, this is what the solution above does. It uses animation.isPlaying to determine if the animation is playing. In more detail, it uses a coroutine to wait until it return false.

All of these solutions are unnecessarily complex. You already have this functionality built into Unity with just two lines of code:

animation.Play( );
yield return new WaitForSeconds( animation.clip.length );

Hmm, this is more elegant than what I did in the CheckEventTime() method. However, what I presented also gives asynchronous notification at the end of the period. Now at this point I may be getting a bit tangential, so maybe it should move to another thread, but--I haven't discovered a lot of patterns in Unity for asynchronous notification. My current project is my first in Unity, so it might be that I'm trying to shoe-horn familiar paradigms better suited to different environments into Unity, but I'd be interested to hear how other people have gone about this. Anyone?

That's true. I was just crafting my response to address the original issue and nothing more. The OP was wondering if it was possible to just call a simple yield function to wait for animation complete. It didn't sound like the OP wanted a whole system designed to deal with timing issues, just something small and simple... so that's what I gave.

Actually animation.clip is the default animation, see http://docs.unity3d.com/Documentation/ScriptReference/Animation-clip.html. I am currently trying to wait until the currently played animation (not the default one) finishes after I called animation.Play("some_other_clip") and of course this doesn't work correctly (it either waits for too long or too short). For me this worked: yield return new WaitForSeconds(this.animation["some_other_clip"].length); See http://docs.unity3d.com/Documentation/ScriptReference/AnimationState-length.html

ah, good clarification.

Waiting for the length of the animation is not a good idea because it does not take the playback speed into consideration. If you play an animation at twice the original speed, the yield will still wait for the duration the animation would take at its original speed.

I am fairly new to unity so I may be doing something REALLY wrong here but I had the same problem which I solved very simply;

//Code before animation
animation.Play("yourAnimation");
while (animation.IsPlaying("yourAnimation")){
    yield;
}
//Code to execute once animation is complete

I first tried with nothing in the while loop but that caused a meltdown - yeild works well!
If you need it super accurate you could (possibly) try something like yeild (0.01) or something?
But the above is a super simple way I think to do what you need!

If you have started a named clip with

this.animation.Play("some_clip");

then you can wait until it is finished with

yield return new WaitForSeconds(this.animation["some_clip"].length);

See Unity - Scripting API: AnimationState.length and Unity - Scripting API: AnimationState

If you found your way here but you’re using the newer Animator system in Unity,
you can achieve this like this:

  do
  {
    yield return null;
  } while ( myAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f );

To add to this old thread, a decent implementation of the idea is to just wait for an animation event.

yield return WaitForAnime();

bool receivedAnimationEvent;
        
private IEnumerator WaitForAnime()
        {
            do
            {
                yield return null;
            } while ( receivedAnimationEvent != true);
        }

public void AnimationEventListener()
        {
            receivedAnimationEvent = true;
        }

I’ts prety easy. Just place an event to the end of the animation then edit it to take a function (a public function that you have created in a script).That function whill do everything you code in your script when the animation is in the moment of that event.

For more details: http://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

Absolutely not, anim events are incredibly unreliable