QuickTip: Execute Code After Animaiton

This entry is part of a series, Quick Tips»

Hey there. Here is a new series of quick, but hopefully useful tips for you.

We start of by executing some code after an animation has run once!

If you are coding on the timeline, then go ahead and do that, no need to be reading this post! (I would NOT recommend doing that – follow MJW’s avoider tutorial instead to get going)

 

If you’re not coding on the timeline, it’s actually really simple, just take a look at the code:

package
{
	import flash.display.MovieClip;
 
	public class MainExecuteAfterAnim extends MovieClip
	{
		public var animation:MovieClip;
 
		public function MainExecuteAfterAnim ( )
		{
			animation.addFrameScript ( animation.totalFrames - 1, stopAnimation ) ;
			animation.gotoAndPlay ( 1 ) ;
		}
 
		private function stopAnimation ( ) :void
		{
			animation.stop ( ) ;
			//other code
		}
	}
}

The reason i made animation.totalFrames - 1, is that addFrameScript is for some reason null based. This means it starts counting at 0, while the movieclip starts counting at 1. If you for an example want to add a frame script to frame 1, you need to call addFrameScirpt ( 0, nameOfFunction ) .

I basically made an example of it here (it would be no good if I just ran the code above, so I have added some event listeners and stuff). Click it to play the animation once. When the animation is finished, you can click it again to reset.

(Either JavaScript is not active or you are using an old version of Adobe Flash Player. Please install the newest Flash Player.)

Happy coding :)

Posted on January 13th, 2010
Filed under ActionScript 3, Flash, Tutorial |

One Response to “QuickTip: Execute Code After Animaiton”

  1. Andy Moore
    August 31st, 2010 at 02:02

    Wow. I had no idea this function existed. Huh. I guess you’re going into my google reader now. :)

Leave a Reply