Actionscript 3 Cutting off your Tweens? Here’s why…

July 19th, 2009

One flash project that I’ve been working on recently is a dynamic image carousel for a website header. All was going well – the carousel was loading external images, spinning correctly, and could be interacted with via the mouse pointer. The header called for the carousel to load off screen and move up into view once the load was complete. No problem, a simple tween should do it…

The Problem

At first that was fine, the carousel loaded and tweened as expected, but after making a few changes to other parts of the header and testing a few more times, the tween stopped short leaving the carousel half visible and half off screen. The irritating thing was that it was seemingly random. Sometimes it would make it all the way, sometimes it would get part way and stop, and occasionally it would appear not to move at all.

After doing some research I discovered that the likely cause of the problem was the garbage collection process. The garbage collector is always running in the background of your flash projects, cleaning up any resources that are no longer needed – variables, listeners, even tweens. It turns out that once you start a tween, unless it was created using a static method there’s no longer any reference to it, and therefore flash tags it as eligible for garbage collection.  When the collector comes around, it deletes your tween stopping it in it’s tracks however far it’s got.

The Solution

The solution for this problem is thankfully pretty simple. By creating a tween using a static method it is being referenced elsewhere in the code, keeping it out of the way of the garbage collector. The simplest way to do this is to use a premade Tweening class library, such as Tweener. This replaces flash’s built in tweening engine, giving increased stability and flexibility.

The Quick Fix

Chances are, if you searched for this problem, you’re having it in a project you’ve already started, and you might not want to switch over to using a whole new class. This fix is for you. Simply creating a “Dictionary” object and storing references to your tweens in it will keep them safe from garbage collection. You just have to be careful to remove them from the dictionary once the are completed, to avoid bogging down your file with unnecessary tweens. I used to do this manually, but recently I discovered these classes created by Matthew Tretter. Once imported, they can be used just as the original classes, but the GarbageCollectionShield Class will keep your tweens safe until they are finished.  Also included in the download are replacements for the Loader, Animator, URLLoader, and Timer classes, for which the same problem exists.

Happy Tweening!

Leave a Reply