Warning: Declaration of thesis_comment::start_lvl(&$output, $depth, $args) should be compatible with Walker::start_lvl(&$output, $depth = 0, $args = Array) in /nfs/c03/h08/mnt/50298/domains/gamedev.michaeljameswilliams.com/html/wp-content/themes/thesis_18/lib/classes/comments.php on line 0

Warning: Declaration of thesis_comment::end_lvl(&$output, $depth, $args) should be compatible with Walker::end_lvl(&$output, $depth = 0, $args = Array) in /nfs/c03/h08/mnt/50298/domains/gamedev.michaeljameswilliams.com/html/wp-content/themes/thesis_18/lib/classes/comments.php on line 0

Warning: Declaration of thesis_comment::start_el(&$output, $comment, $depth, $args) should be compatible with Walker::start_el(&$output, $object, $depth = 0, $args = Array, $current_object_id = 0) in /nfs/c03/h08/mnt/50298/domains/gamedev.michaeljameswilliams.com/html/wp-content/themes/thesis_18/lib/classes/comments.php on line 0

Warning: Declaration of thesis_comment::end_el(&$output, $comment, $depth, $args) should be compatible with Walker::end_el(&$output, $object, $depth = 0, $args = Array) in /nfs/c03/h08/mnt/50298/domains/gamedev.michaeljameswilliams.com/html/wp-content/themes/thesis_18/lib/classes/comments.php on line 0
AS3 Avoider Game Part 8: Adding a Preloader β€” Michael James Williams

AS3 Avoider Game Tutorial, Part 8: Adding a Preloader

by Michael James Williams on February 24, 2009 · 185 comments

in Avoider Game Base,Tutorial

In the coming parts of this tutorial, we’ll be adding music, sound effects, and multiple levels, possibly with a range of different backgrounds and other images. These assets all make the game larger, meaning it takes longer to load. Therefore, in this part of my AS3 and Flash CS3 conversion of Frozen Haddock’s avoider game tutorial, we’ll create a *preloader*, to make sure everything is downloaded before the game can be played, and give the user some idea of how long this will take.

It’s a long tutorial, but that’s because I’m going to explain to you how and why everything works, rather than just give you a method to apply. Once you’ve gone through this, though, you’ll be able to use the same techniques to create a preloader for any other Flash game, movie, or application.

As usual, you can click the image below to see what we’ll have by the end of the tutorial — though with the SWF currently coming in at around 10kB, I don’t think you’ll see it load!


If you’ve not been following the tutorial, grab the zip file of the game so far here and extract it somewhere. Otherwise, copy the files you’ve been working on so far to a new folder, as usual.

Open the FLA file, and let’s get started.

Things are different in CS4! If you run into trouble preloading your game with any version of Flash, I recommend you read this comprehensive tutorial on Activetuts+. It’s great, and it covers everything.

###Why Bother With a Preloader?

Before we take the time to code a preloader, let’s look at what happens if we don’t have one. Now, as I said, my SWF is currently 10KB, a size so small that my connection can download it in under 40 milliseconds. Yours is probably similar, so how can we run any sort of test without cramming in a bunch of huge bitmaps or mp3s or whatever to artificially pad out the size?

Well, fortunately, the standalone Flash player has a way of simulating different download speeds. With your FLA file open, test your game in the usual way (*Control > Test Movie*), and in the Flash player window that pops up, select *View > Download Settings > 14.4 (1.2 KB/s)*:


Now, click *View > Simulate Download*:


The stage will be grey (or whatever colour you’ve set the document’s background to be) for about eight seconds, and then the usual menu screen will appear. So that’s what it’ll look like to anyone browsing the web with a modem from 1992.

Obviously, this isn’t very user-friendly. The user has no idea how long they’re going to have to wait to play, or even if the game is loading at all. There’s also a possibility that the MenuScreen (and thus the Start button) will load before some of the rest of the game (like the background music we’re going to add in Part 9), so the user could begin playing before the game’s even ready, ending up playing in silence or without some of the images appearing. Not good.

A preloader, then, has two main functions:

1. Stop the user from playing the game before it has completely downloaded
2. Let the user know that the game is downloading

There is a third, optional, function:

  1. Entertain the user, keeping their attention while they wait

Let’s start with Number One.

###Wait For It…

Actually, we’ve already solved #1, in a way. Right-click any of the symbols in the Library and view its Properties:


See that box marked “Export in first frame”? It’s checked by default. Flash won’t run any AS3 code until **all** of the symbols marked “export in first frame” have been downloaded — and since the MenuScreen is added to the stage using code, rather than being dragged there manually by us, it won’t appear until everything has loaded. Great! Well… sort of.

The problem is, this means we can’t run any other code until everything has loaded, which means we can’t write any text to the screen or display a cute animation or anything; we’re stuck with that grey rectangle. Dang.

What we need to do instead is gain control of the code as soon as possible, *before* all the assets have loaded, and simply wait until everything is ready before we display the MenuScreen. Ideally, we’ll have some sort of “Loading” symbol that is downloaded before everything else which can be displayed from the start.

Unfortunately, this is quite a tedious process. Get ready to be irritated!

###Who’s On First?

Like I said, Flash won’t run any code until everything marked “export in first frame” has been downloaded. So, the first thing we need to do is go through *every single symbol* in the library, open its properties, and uncheck that box, if it’s enabled. Ugh. Sorry. (If anyone knows of an Extension that does this for you, I’d be most grateful to hear of it.)

**EDIT:** Bert Neyens let me know that, if you’re using Flash CS4, you can hold SHIFT or CTRL (or Command on a Mac, I guess) while clicking items in the library to select several at once. Then if you right click any one of them and select *Properties*, you can uncheck “export in first frame” and it will apply to all of them. Sadly this doesn’t work in Flash CS3, but this is a real time-saver for anyone running a later version. Thanks Bert πŸ™‚

As you go through, you may find this error message pops up:


That’s my fault (oops). It’s because I told you to put “Counter” as the base class for some of the symbols, which is incorrect. Change it to *flash.display.MovieClip* and it’ll be fine.

Some of the symbols won’t allow you to click the box, because we won’t have selected “Export for ActionScript”. In that case, don’t worry about it and move on.

Once you’ve gone through all that, try running the game. You’ll get one or more errors saying:

Error 1120: Access of undefined property [something]

What’s happening here is that Flash is being a little too clever for its own good. You see, if you have something in the library but not on the stage, Flash assumes you don’t need it, and doesn’t include it in the SWF when it makes it (though it does include all the AS files). So in the MenuScreen, for example, Flash has all the code regarding *startButton*, but because the MenuScreen symbol itself is not included in the SWF, and because that’s the only place we tell Flash that *startButton* is actually a button, Flash gets all confused and says it doesn’t know what *startButton* is.

“Export in first frame” tells Flash to treat the symbol as an object that is on the stage in the first frame of the movie. Now that we’ve unchecked it, the objects aren’t getting built in to the SWF. To fix this, we’re going to have to bend the rules I set out way back at the start of Part 1.

###The Three Frame Technique

To summarise: we need all of the library objects on the stage, but we can’t have them in the first frame because Flash won’t run any code until they’re all loaded if we do that. Obvious solution? Put them in the second frame!

Just like we did with the buttons in Part 4, and the Clock in Part 5, we need to add a new keyframe to the timeline. This time, however, it’s the timeline of the stage itself we’re dealing with.

In your FLA, make sure you’re not looking at any symbol in particular — there should only be the blank grey rectangle of the stage on the screen. Now, right-click the second frame of the timeline and choose *Insert keyframe*:


This frame is going to hold all of our symbols (and, later, sounds). Since Flash only waits until it’s loaded everything on the *first* frame before running any code, putting everything on the second frame will let us include all of the assets in the SWF *and* gain control of the code before everything is done downloading.

We could just drag everything from the library into this frame, but this causes a little problem when it comes to sound files (I’ll go over this when we add music) and is generally messy. Instead, I’m going to introduce a technique I learned from this excellent tutorial by Jeff Fulton of 8bitrocket. (Thanks Jeff!)

It’s simple, really. First, create a new symbol (*Insert > New symbol*), of type movie clip, called *AssetHolder*. Don’t bother exporting this for ActionScript, we’ll never reference it in code. Now, edit this AssetHolder (double-click it in the library if it doesn’t open automatically) and just drag everything from the library into this second frame — everything except AssetHolder itself, that is! You can do this quickly by clicking the top item in the library, holding down shift while clicking the bottom item, then dragging the entire list over.


Yikes, what a mess. Get back to the main stage by clicking the *Scene 1* button. Make sure you’re looking at the *second* frame, and drag *AssetHolder* from the library onto the stage.


We might as well place it outside of the visible area (dark grey rectangle) to ensure it doesn’t get seen.

If you save the game and run it now, you’ll get the following error message, repeated about a million times:

ArgumentError: Error #1063: Argument count mismatch on Enemy(). Expected 2, got 0.
	at flash.display::Sprite/constructChildren()
	at flash.display::Sprite()
	at flash.display::MovieClip()

What? Flash is playing frame 1, then frame 2, then 1, then 2, over and over again in a loop. Each time it gets to frame 2, it tries to create an Enemy, because there is an Enemy symbol inside the AssetHolder which is on frame 2. But Enemy objects require two parameters to let them know where to start, and Flash doesn’t know to provide these! Thus, we get this error.

Solving it is easy. We just stop Flash from looping through frames 1 and 2. Sadly we have to break another of the rules from Part 1.

Right-click the first frame of the main timeline and select *Actions*.


The *Actions Panel* appears. This lets you write code that is run when a specific frame is reached. A lot of AS2 games were written by coding entirely within the Actions panel (in AS2, symbols have their own Actions Panel, kind of like how in AS3 they can have their own class file). We just want Flash to stop at this frame and not go onto frame 2. The code for this is ridiculously simple:


Close the Actions Panel, save the game, and try to run it. We get an error message, but it’s a good sign!

TypeError: Error #1009: Cannot access a property or method of a null object reference.
	at MenuScreen()
	at DocumentClass()

Open up *DocumentClass.as* (can you believe we haven’t written anything in the class files so far?) and the cause is obvious — just take a look at the constructor:

public function DocumentClass() 
	menuScreen = new MenuScreen();
	menuScreen.addEventListener( NavigationEvent.START, onRequestStart );
	menuScreen.x = 0;
	menuScreen.y = 0;
	addChild( menuScreen );

The very first line creates a new MenuScreen, and the error is regarding the MenuScreen. It’s no coincidence. This shows us that Flash is running the code before having loaded everything, which is exactly what we wanted. Let’s get rid of that error by moving that MenuScreen-related code out of the constructor:

public function DocumentClass() 


public function showMenuScreen():void
	menuScreen = new MenuScreen();
	menuScreen.addEventListener( NavigationEvent.START, onRequestStart );
	menuScreen.x = 0;
	menuScreen.y = 0;
	addChild( menuScreen );			

If you save it and run it now, you’ll get no error messages! Sadly, you’ll get no game either. We should probably fix that.

###Are We There Yet?

At the most basic level, we just need the preloader to detect when the SWF has completely finished downloading, and then display the MenuScreen. Guess what? Time for another event listener!

public function DocumentClass() 
	loaderInfo.addEventListener( Event.COMPLETE, onCompletelyDownloaded );

– **loaderInfo** is a built-in object that holds information about, well, how much has loaded.
– **Event.COMPLETE** is dispatched by *loaderInfo* when the entire SWF has downloaded.

Even though this is such an important event that it’s part of the base *Event* class, rather than *DownloadClass* or whatever, we still have to import it:

import flash.display.MovieClip;
import flash.events.Event;

And of course we need to write an event handler:

public function onCompletelyDownloaded( event:Event ):void

I’ve gone ahead and made it run the MenuScreen code that was originally in the constructor, here.

Logically, this all makes sense, right? It should work now. It doesn’t, of course. There’s one more hoop we have to jump through.

See, even though all the library assets are in the SWF, Flash can’t access them until it reaches the frame of the movie that they’re on, i.e. frame 2. (Just– just go with it, OK? We’re all in this together.) Before we can use anything, then, we have to get to frame 2. But we already saw what happens when we try to run frame 2; we get an error because of the Enemy’s constructor function. This means, then, that we need to add a *third* frame where the actual gameplay can take place.

Back in the FLA, right click frame 3 in the timeline and *Insert Blank Keyframe*.

(Make sure it’s a blank keyframe!)

In *DocumentClass.as* again, alter your *onCompletelyDownloaded()* function:

public function onCompletelyDownloaded( event:Event ):void

*gotoAndStop(3)* makes the Flash move directly to frame 3 without passing through frame 2 (or collecting Β£200).

Save it, cross your fingers, hold your breath, and run it…


Ahhhhh. Congratulations, that’s one of the most irritating things in Flash game development *and you’ve done it*. Try simulating the download again — you’ll get the grey screen for a few seconds and then the MenuScreen will suddenly appear, just as when we tried it at the start, 2,000 words ago. This time, however, we have control of the code.

###Showing Progress

This is all well and good, but what about the second function of a preloader, “Let the user know that the game is downloading”? Don’t worry, that’s much easier. The *loaderInfo* object contains two important properties:

– **bytesLoaded**, the number of bytes of the SWF that have been downloaded so far.
– **bytesTotal**, the total size of the entire SWF, in bytes.

It also dispatches another event: a *ProgressEvent* of type *ProgressEvent.PROGRESS*, which fires off every time a little bit more of the SWF is downloaded. Naturally we can use these in combination.

Add another event listener to the constructor of your document class:

public function DocumentClass() 
	loaderInfo.addEventListener( Event.COMPLETE, onCompletelyDownloaded );
	loaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgressMade );

Import *ProgressEvent*:

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.ProgressEvent;

And create an event handler:

public function onProgressMade( progressEvent:ProgressEvent ):void

In Part 6 I introduced you to comments. Now I’m going to introduce another important tool for development: the *trace()* function. This is used for looking at data inside the SWF while it’s running; anything inside the brackets of *trace()* will be output to a window called, appropriately, the *Output Window* (make sure *Window > Output* is checked if you can’t see it).

Let’s try this out. Add this line to your new event handler:

public function onProgressMade( progressEvent:ProgressEvent ):void
	trace( loaderInfo.bytesLoaded, loaderInfo.bytesTotal );

As you can see, *trace()* accepts multiple parameters. If you save and run the game, and simulate a download, you’ll see the Output window slowly fill up with numbers:


As you can tell from the code, the first number is how many bytes have “downloaded”, and the second is the size of the SWF. When the two numbers match, *loaderInfo* fires off the *COMPLETE* event, and the MenuScreen appears.

We can show the percentage loaded with a little arithmetic:

public function onProgressMade( progressEvent:ProgressEvent ):void
	trace( Math.floor( 100 * loaderInfo.bytesLoaded / loaderInfo.bytesTotal ) );

Dividing the one by the other gives us a fraction, multiplying this by 100 gives us a percentage, and *Math.floor()* removes everything after the decimal point.

All we need to do now is display this information to the user. Ah, if only we had a class designed for taking numerical data and displaying it in a graphical way. Oh wait! That’d be the *Counter* class we made back in Part 5.

Now I already explained back then how to make a symbol based on the Counter class, and I’m not going to repeat myself here. It doesn’t matter what you want your preloader to look like — a spinning thing, a progress bar, a simple piece of text saying “loading…”, whatever — just make it **simple**, because it has to download quickly. Personally I’m just going to go with this:


That’s a movie clip called *LoadingProgress*, exported for ActionScript, **and also exported in the first frame**. (It needs to be exported in the first frame because it has to load before the code that’ll update it is run.) The dynamic text field holding the number has an instance name of *percentDisplay*.

It needs a class file, so create one called *LoadingProgress.as* and save it in the *Classes* folder. Here’s the code to go in it:

	import flash.text.TextField;
	public class LoadingProgress extends Counter
		public function LoadingProgress()
		override public function updateDisplay():void
			percentDisplay.text = currentValue.toString();

This is almost identical to the class for the Score. Alter it to match your own loading display (see Part 5 for more help).

There is one difference I’d like to make. *Counter* and *LoadingProgress* only allow their internal values to be updated through the *addToValue()* function. This is inconvenient, since we don’t know *how much to add* at any given point, only what the value *should be*. Let’s create a new function for setting that:

public function setValue( amount:Number ):void
	currentValue = amount;

You could add this function to *LoadingProgress*, but I’m actually going to add it to *Counter*, since we might need to use it in something else later. Of course, *LoadingProgress* will gain the use of this function, since it extends Counter.

Nearly there! Head back to the document class and set up the *loadingProgress* object:

	public class DocumentClass extends MovieClip 
		public var menuScreen:MenuScreen;
		public var playScreen:AvoiderGame;
		public var gameOverScreen:GameOverScreen;
		public var loadingProgress:LoadingProgress;
		public function DocumentClass() 
			loadingProgress = new LoadingProgress();
			loadingProgress.x = 200;
			loadingProgress.y = 150;
			addChild( loadingProgress );
			loaderInfo.addEventListener( Event.COMPLETE, onCompletelyDownloaded );
			loaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgressMade );

Note that we’ve put it in the constructor function. This is fine! Don’t worry. It’ll work, because we’ve exported it in the first frame — meaning it’ll load before the code referring to it is run.

If you save it, run it, and simulate a slow download, you’ll see it:


It’s stuck at zero, of course, because we haven’t written any code to update it. Naturally that goes in the *onProgressMade()* function. I’m going to replace the *trace()* statement with it:

public function onProgressMade( progressEvent:ProgressEvent ):void
	loadingProgress.setValue( Math.floor( 100 * loaderInfo.bytesLoaded / loaderInfo.bytesTotal ) );

Save it, run it, and simulate another download:



###Wrapping Up

There’s one more thing we need to make sure gets included in the SWF: fonts. For static text, there’s no problem; the font is automatically included. But for dynamic text, this isn’t the case; if the player does not have the font installed on his own PC, he’ll just see one of his computer’s default fonts, like Times New Roman.

Fortunately, it’s very simple to embed these fonts into the SWF. Just select the dynamic text field in question, click the *Embed…* button in the *Properties* panel, and select all of the characters you’re going to need. Don’t select *All characters* — I did this once, and it added 10MB to the size of my SWF! Just select the essentials — uppercase and lowercase letters, numerals, punctuation, and basic Latin are usually enough. Oh, and if you use the same font for several different dynamic text fields, you only need to embed it for one of them.

By the way, you might find that your progress meter starts at some high number (mine starts at 60%!). This is because we’re dealing with such a small file that a large proportion of the SWF is taken up by code and the preloader itself. As we add sounds and images, this problem will go away.

Just to be clear, from now on when you add anything new to the library, you shouldn’t export it in frame one (unless it’s part of the preloader), and you should add it to the *AssetHolder* object. Otherwise the game won’t load properly.

If you’re looking for a challenge this week, try doing something related to the third function of a preloader, “Entertain the user, keeping their attention while they wait”. What can you do without using so much code and graphics that the preloader takes ages to load? If you’re looking for inspiration, try the 25-Line ActionScript Contest, TweetCoding, and the 4k Competition πŸ˜‰

Big thanks to Jeff Fulton for letting me borrow his work on preloaders in AS3 & CS3. His blog post is the best I’ve ever come across on the subject, so check it out if you want more detailed information. Heck, check his blog out regardless, it’s always good πŸ™‚

As always, you can download a zip with all the files relating to this part of the tutorial here.

Next week we’ll add music and sound effects (partly to justify the work of writing a preloader). If you’ve got any music of your own you want to use, now’s the time to find it πŸ™‚

{ 34 comments… read them below or add one }

Michael Williams July 23, 2010 at 11:59 am

Hey all, Zach Zurn of TechAssist sent in this comment, which my overprotective spam system is keeping out. I think it’ll be helpful. Thanks, Zach!


I was having a problem with the preloader only starting at 50%. It makes sense that the preloader would start at 50%, because the file is so small that 50% of it is downloaded by the time the basic files are downloaded.

At this point it’s a presentation issue, we want the preloader to properly display the percentage of loading left to go. I handled this by having 2 additional variables and some if statements.

The Variables are these:

private var loadedFirst:Boolean;
private var loadedFirstNum:Number;

I initialize those in the constructor function:

loadedFirst = false;
loadedFirstNum = 0;

And then in the onProgressMade looks like this:

public function onProgressMade (progressEvent:ProgressEvent):void
                       if (loaderInfo.bytesLoaded == loaderInfo.bytesTotal) //If the first progress event is, set the progress to 100%
                       else if (loadedFirst == true) //Otherwise check if the loadedFirst variable has been set and use that to show a correct percentage
                               loadingProgress.setValue(Math.floor( 100 * (loaderInfo.bytesLoaded - loadedFirstNum) / (loaderInfo.bytesTotal - loadedFirstNum)));
                       else //If this is the first progress event, set the prebytes so we can take those out of the equation
                               loadedFirstNum = loaderInfo.bytesLoaded;

                           trace("Set Prebytes: " + loadedFirstNum);
                           trace("Total Bytes: " + loaderInfo.bytesTotal);

                           loadedFirst = true;
                           loadingProgress.setValue(Math.floor( 100 * (loaderInfo.bytesLoaded - loadedFirstNum) / (loaderInfo.bytesTotal - loadedFirstNum)));

I hope this helps, I was kind of stumped for a bit on how to fix this.

Kevin Neal September 6, 2010 at 10:05 pm

Now all we need is a tutorial on adding a sponsors preloader πŸ™‚ I’m not sure how many people have gotten that far, but its a slightly different ball park. Trying to add an swf preloader, any suggestions?

wp September 10, 2010 at 12:42 am

What is the point of the AssetHolder? Can’t we just drag everything into the 2nd frame if we’re not even using it? I see that in part 9 you do that with the sounds.

Pirill September 11, 2010 at 9:39 am

Hello! I just wanted to say that your preloader instructions worked flawlessly in Flash CS5, so I don’t really see why it would be any different from the other versions of Flash. If need be, I can post my game here, but there’s nothing really different from what you’ve done.

Michael Williams October 5, 2010 at 1:04 am

I’m back from holiday!

@Kevin: Hey Kevin! I’ll send you an email soon πŸ™‚

@wp: The AssetHolder just makes it a little easier to deal with, I find. I guess you don’t need to use it.

@Pirill: Oh — great! Thanks for letting me know πŸ™‚ I have no idea what the issues are then :/

Sam October 16, 2010 at 9:24 pm

This tutorial and by this i mean the whole thing is just amazing. great job !

Mr.Awesome December 9, 2010 at 2:21 pm

Hi Michael,i have this mistake(1061:Call to a possibly undefined method setValue through a reference with static type LoadingProgress)
i did somehing wrong? o_O

Jack D January 8, 2011 at 2:28 am

Good evening, Michael, and a happy new year to you. I am an ignorant fool that has ascended to great heights using this tutorial as his stepping stone. My first game after reading this, was “Wild Flatmates Appear in Tall Grass” on Kongregate (a lousy PokΓ©mon clone, but it nevertheless impressed at least myself, as I had no prior experience with programming or computers for that matter). Now, half a year later – I am knee deep in more serious business – and I was scavenging the Internet for information on the subject of preloading, when I came to think of my old master.

You, that is.

I kneel before you, Sensei, humbly wishing to obtain some of your godly wisdom – especially wisdom concerning multiple preloadings:

If a game is to happen in several “scenes”, is there an easy way to preload images and sounds connected to one particular scene as one is about to enter it? Make several assetholders that loads their content when you call for this function? Like starcraft II, you click “start game” and THEN it loads the current map, players and models.

Thanks in advance,

Andrea January 27, 2011 at 7:24 pm

I have cs5 and also dont get the preloader to work… there is just the stage, with this 1-5 points.

i putted(?) a trace into the constructor of the DocumentClass:

       public function DocumentClass()
                        loadingProgress = new LoadingProgress();
            loadingProgress.x = 200;
            loadingProgress.y = 150;
            addChild( loadingProgress );
            loaderInfo.addEventListener(Event.COMPLETE, onCompletelyDownloaded);
            loaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressMade);

the result is, that “A” shows up, when the menuscreen shows up, so that i conclude, that te constructor, or better the whole class is loaded in frame 2

i hope someone can help me with this infos i gave…

Daniel March 12, 2011 at 1:18 am

Hi everyone

I am making this game in Flash CS% and can’t seem to get the trace function right at the start of this section to work.
Any ideas would be great

many thanks
by the way this is a great tutorial

Aspiring March 17, 2011 at 7:20 am

Everything is working but I feel like I’ve done something wrong becuase my file is 6x what Michael’s is.

Bryon March 25, 2011 at 11:00 pm


I am using CS5 as well. Do you mean this trace line?

trace( loaderInfo.bytesLoaded, loaderInfo.bytesTotal );

Do you get an error? Or is nothing showing in your output?

If its an error. Please post it.
If it is not outputting, double check your trace line. If it all looks ok then most likely you did something wrong before that, and the function your trace is in, is never getting called.

Bryon March 26, 2011 at 6:26 pm

Also, I noticed a lot of people are saying they are looking at a blank (Stage Color) screen, before their preloader shows up and that it starts at a higher percent than 0.

Well I messed around a bit and there are a few reasons this happens I believe.

Even if you make something very simple, say one text box that is your preloader. The lowest I could get mine was about 2kb in size. This size contributes to the total size of your swf. I think you could find the total size of your preloader, then subtract it from your bytes total when you do your calculations for percentage. Not worth it in my opinion.

Now if you are testing this, and your overall file size is very small. Then you would set the download speed to its lowest setting (1.2kb/s)

It will not go into the constructor of your document class until that 2kb preloader is loaded. This in turn will leave you looking at a blank screen for about 2 seconds ( The time it takes at that speed for your preloader to load )

The good thing is once you put your game out onto the web, even someone with a 56k connection, they will not see that blank screen because your preloader will load in a few short milliseconds.

If you want a very detailed preloader, with a large file size, consider adding a sponsor to show on your screen while your preloader loads. Sort of like a preloader, for your preloader.

Hope this is correct and that it made sense!

Tyler S June 11, 2011 at 3:29 am

Hey Michael,
I’m not sure why, but my preloader does not come up for like 7 seconds after pressing simulate download. I even tried downloading a copy of your version and it still did not work right away. I was just wondering if you had any idea why this would be happening.

Thanks in advance

Marc June 23, 2011 at 7:34 pm

Thanks for the tutorial! Really good step-by-step one!

Duckling June 30, 2011 at 1:44 am

I couldn’t help but notice that you mentioned the need for Actions code writing, and I’d like to insist that it’s never necessary; the undocumented piece of code called addFrameScript takes care of the issue.

addFrameScript ( z - 1, thingToDo );

thingToDo () :void {
// do that which it is that this is to do, on frame z;

One can put this in the Document Class for the project, and the class-scripts-only rule will not have been broken. I find it satisfying to be able to work around the problem in this manner, and anyone else who would do so should know about this function.

Cleyton July 27, 2011 at 5:07 am

Thanks man, the tutorial is very good!!!

Averlyn August 17, 2011 at 4:52 am

Hi Micheal, thanks so much for this tutorial – it’s a real lifesaver! =P

I’ve been having trouble with the counter functions (sometimes there’s problems with the addToValue function) throughout the course of this tutorial and now I’ve got another related to the setValue function. I get the following error:

“TypeError: Error #1006: setValue is not a function.
at DocumentClass/onProgressMade()”

In my file, setValue is in blue (like private, function, addEventListener), so I thought, OK maybe the name’s clashing with something else, but even after changing it, it doesn’t work. Sorry if this is an easy problem to solve – I’m still a noob. x__X

Ang October 21, 2011 at 12:35 pm

Hey Michael, if i have a movieclip inside a movieclip , lets say movieclip “a” inside movieclip “b”, do i have to put both movieclip to the AssetHolder or “b” is suffice? Thanks man! πŸ™‚

Michael James Williams October 21, 2011 at 8:36 pm

Hey Ang,

Nope, just put b in there!

Kristen November 7, 2011 at 7:19 am

I have been having a heck of a time with the Preloader. I am using CS5, and have based my game on this tutorial (it’s awesome!! Thank you!!), but the preloader doesn’t seem to work for me the way I’d expect. I tried going through tutsplus.com too (and maybe this confused me more, since it was explained a little differently), but with the same result… a blank screen for about 50 seconds, then the preloader appears (at “75”) and counts up to 100 before loading the game.
I’ve downloaded your files and found my “Simulate Download” yields a blank preloader also.
The TutsPlus site recommends loading the DocumentClass in the second frame, then placing the loading bar in frame 1, but I get a lot more errors this way.
SO my question is… is this a CS5 thing? Have things changed that much? Is there some magic code that makes my preloader only appear after the files are 75% downloaded?

Tomaz December 28, 2011 at 10:25 am


try Publish Settings -> ActionScript Settings -> Export classes in frame: 2

Jack January 12, 2012 at 12:01 am

Hey Michael, thanks so much for this tutorial. I’ve managed to get myself through most of it, but now I’m at a roadblock. Initially, I was having a similar issue to Sean who posted a while back, where I would just get a white screen for a while, the Output would declare:


and then when the game loaded, I was getting my percentDisplay down below the playable screen and it was only showing “0”

I fiddled around a bit trying to make that work, and reading the other tutorial you recommended, and now I am getting this error when I try to run things:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LoadingProgress/updateDisplay()
at Counter/reset()
at Counter()
at LoadingProgress()
at DocumentClass()

Which seems like something really obvious and fixable, but I am brand stinkin new at this stuff. I’m an artist, here :P. Any help would be awesome, and I am going to download your next part and cross-reference in a minute, just thought maybe someone would still be using this board πŸ™‚


Jack January 12, 2012 at 1:02 am

Ah! I think I’ve solved most of my n00b problems!

Firstly, I missed the part where you mentioned to replace the trace statement with loadingProgress.setValue. Maybe you could give that some cushioning or something between those two big similar pictures? I don’t know, maybe it was just me being hasty, cause now that I look again, it is obvious that it mentions it.

Secondly, and probably the reason I didn’t do the above, is that my actual text field was not centered in the LoadingProgress object, which caused it to show up in a strange place when I set my coordinates to be in the middle of the screen.

Now I’m just running into the issue that my first frame is half the size of my whole swf because of a packed document class, which other people have already noted. after I get through some more of the tutorial, I will try to figure out a way to remove this preloader from the document class, or maybe it is actually covered later on.

Oh, one other thing that might help some people; I have noticed that using:

override public function reset():void { }

in my LoadingProgress.as has helped avoid some issues with the loading percentage going back and forth and being generally ridiculous.

Guga February 12, 2012 at 10:21 pm

Hey Michael, thanks for the tutorials. It’s really helpful.

I’m experiencing problems with my pre-loader. I deselected every “export to frame 1” box except for the preloader one, but my code is blocked until the whole movie is downloaded.

I mean, when I simulate my download, everything’s just white. After the first frame is downloaded, I get the default animated dots preloader. After all three frames are downloaded, my code finally starts working. I put a “trace” at the DocumentClass constructor, and I get my output only after the whole file is ready, instead of after only the first frame. I really have no idea why, I followed every step in detail.

Thanks in advance to anyone that could help me!

Chris March 23, 2012 at 5:35 am

In CS5, it doesn’t look like the progress listener:

loaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgressMade );

is being triggered. I put a trace(‘test’); in there an nothing was outputted.

Madcowe May 21, 2012 at 6:06 pm

My problem is also that I am using flash CS5 and the preloader does not work…

If anyone finds a way to fix this could you please say it here or mail me?

Jan August 22, 2012 at 6:59 am

Like Chris said,
the progress listener seems not to be firing in Flash CS6.
loaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgressMade );

What’s the problem here?

Taerzik September 25, 2012 at 6:00 am

Michael, thanks for the great tutorial!

I read the entire Flash 5 Bible and over half of the CS3 Bible trying to convert from AS2 – in the end I could barely pull the concepts together. This hands on practice is what I needed.

To Anyone:
Having difficulty with the loader code in CS5.5 / AS3
I can trace the percent loaded with the simulated download but when I try to send it to the text box it comes up as NaN every time.
I tried a few other things, even tried just putting the bytes loaded or total but everything is coming up NaN.
I’ve looked around a bit but can’t seem to find a straight answer to this problem.
If anyone has a clue…

Thanks again Michael.

Kaushal September 27, 2012 at 7:03 am

not getting any error even if i uncheck export to frame 1 in all objects. On simulating in shows grey screen for sometime and appears the menu screen. Even i tried with your code, I am using CS6.

Cody Eves November 2, 2012 at 5:44 pm

Okay, I’ve followed everything in this tutorial thus far, but yet I keep getting an error when I try to run the game. Here it is:

ArgumentError: Error #1063: Argument count mismatch on Enemy(). Expected 2, got 0.
    at flash.display::Sprite/constructChildren()
    at flash.display::Sprite()
    at flash.display::MovieClip()
    at MenuScreen()
    at DocumentClass/showMenuScreen()
    at DocumentClass/onCompletelyDownloaded()

I’ve been confused on this for a while, and I really need some help solving this problem.

Zack December 9, 2012 at 11:26 pm

To anyone who is having the problem where “loaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgressMade );” does not fire useing CS5. There is a solution. The process is exactly the same except for two things. The firs is that you need not make or add the AssetHolder MoviClip into the second frame. Second, instead of unchecking all the “Export in frame 1s,” leave them checked and instead go to File > Publish Settings – go to the Flash tab, and then click “Settings” next to “Action Script 3.0.” From there, type in “2” where it says “Export Classes in Fram:” instead of “1.” Last, go to the “Library path” tab and change “Default Linkage:” from “Runtime Shared Library (RSL)” to “Merge into code.” Then click “ok” at the bottom then “ok” again. That should work!

Sunny April 17, 2013 at 2:03 am

Hi Zack your method worked! Thanks!

Ty June 6, 2013 at 2:20 pm

This tutorial seems very useful and will try to implement it into my game. Quick question though, I’m running my game through a Document Class which when it initial loads, has an internal preloader which populates the in-game databases via Embedded XML files. How can I incoporate the population that process with this preloader so it all occurs at once.

Leave a Comment

Writing code? Write <pre> at the start and </pre> at the end to keep it looking neat.

{ 1 trackback }

Previous post:

Next post: