Flash Notes: Preloader
Here’s how to create a preloader in ActionScript 3. The AS2 methods have been thrown out and the new model uses event listeners.
“loaderInfo” is the general state of the SWF as it’s loaded. While it’s loading, you get a progress event, and upon completion, a complete event. Here’s some sample code:
loaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
loaderInfo.addEventListener(Event.COMPLETE, completeListener);
function progressListener(event:ProgressEvent):void {
bar_mc.scaleX = (event.bytesLoaded/event.bytesTotal);
}
function completeListener(event:Event):void {
loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progressListener);
loaderInfo.removeEventListener(Event.COMPLETE, completeListener);
// do something
}
This basically sets up two event listeners, progress and complete. While progress is happening, you get constant updates of bytesLoaded and bytesTotal, with which you can provide the user feedback that something is happening. In this case, it’s just changing the shape of a bar with the instance name “bar_mc” (note scaleX [AS3] rather than xScale [AS2]), but as I’m sure you’re well aware, you could use the result for a percentage indicator, or control an animation.
Note #1: It’s a good habit to remove event listeners when you no longer need them, hence the two lines of code within completeListener. These basically nuke both of these listeners that were in use while the SWF was loading because they aren’t needed once the movie has loaded.
Note #2: I’ve seen example code where “event” within the function is changed to “myEvent” or shortened to just “e”. It’s a variable that is self-contained and can be named anything you like, but it would be good to stick to a convention.
Previous Post:
Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks
(Trackback URL)