Archive for November, 2010

Preloader without a loader-swf in AS3

Wednesday, November 17th, 2010

Here’s one method of loading your AS3 movie, using a preloader class that loads before all other classes.

The flex compiler can actually split up the code for you so one class loads before all others. Even though we’re using the flex compiler to do this we do not have to have a Flex project, it can be a Flash project or a pure actionscript project. If we’re using a Flash project we do have to set the flex compiler path though.

Anyways, the way it works is that in your main class you add the Frame metadata, like this:

package com.flassari {
// Preloader meta tag
[Frame(factoryClass="com.flassari.Preloader")]
// Start of our own application code
[SWF(backgroundColor="#FFFFFF", frameRate="24", width="800", height="600", pageTitle="My preloaded project")]
public class Main extends Sprite
{

The preloader has to extend movieClip, because behind the scenes it is using frames for its magic.
In your preloader class, when it is done loading (by checking if it is at the last frame), your have to instantiate the main class with no strict typing. If you were to use strict typing, the whole application would have to load before the preloader can be shown so that would defeat the purpose of a preloader:

private function onEnterFrame(e:Event):void {
	if (currentFrame == totalFrames) { // If we're at the frame where Main is ready
		// Stop and clean up
		stop();
		removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		// Create the main application and add it to the display list
		var mainClass:Class = getDefinitionByName("com.flassari.Main") as Class;
		addChild(new mainClass() as DisplayObject);
	}
}

Just remember, everything that the preloader references will be loaded before the preloader can be shown, so keep it to a minimum.
Also, because the main class is created before it is put on the stage, be sure not to reference the stage in the constructor.