Game preloader

Generally, Flash games need to be completely download before they can be played. This is why the vast majority of Flash games use preloaders, which force the game to wait until everything has downloaded, while providing a visual indication of the load-progress.

(In the demo below, you can change the download speed as well as the amount that is downloaded)


The preloader we’ll be making consists of three parts:

  1. A “loading bar”, used to indicate the load-progress graphically.
  2. A text field, used to indicate the load-progress as a percentage, e.g. 48%.
  3. A frame script, which takes care of updating the progress indicators as the swf downloads, and sends the playhead to frame 2 when the swf has finished downloading.

Let’s begin by creating a new ActionScript 3.0 document and setting its document properties. Apart from the background color which I’ve set to black, all other properties are left at their defaults.

The loading bar is simply a rectangle with a color of #009999, and dimensions 300×8. Place the loading bar on a separate layer called “Loading bar”. Make sure you convert the rectangle to a movieclip (F8). Name the movieclip “Loading bar”, and give the instance on the Stage an instance name of “loadingBar”. I’ve placed the bar at coordinates 125,170.

Convert to movieclip

NOTE: Make sure you select the top-left registration point.

Place the text field on a separate layer called “Loading text”. The text field’s properties should be set like so:

Text field properties

The only property that is important is the instance name; make sure it’s “loadingText”. You can set the other properties to your liking.

The frame script is very simple. Create a new layer called “Actions”, the frame script will be placed on frame 1 of this layer. A stop() command is used to stop the swf from playing until it’s ready.

1
stop();

Because we want to display load-progress, we need to listen for the ProgressEvent.PROGRESS event, which indicates that a new portion of the swf has arrived and gives us the latest load-progress information. It’s the main timeline’s LoaderInfo object that dispatches ProgressEvent.PROGRESS events, so we need to register a listener with that object. The LoaderInfo object also dispatches an Event.COMPLETE event, which indicates that the swf has completely downloaded. So we’ll also register for that event.

3
4
loaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
loaderInfo.addEventListener(Event.COMPLETE, completeListener);

progressListener() first divides the number of bytes that have been received so far (bytesLoaded), by the size of the swf in bytes (bytesTotal), and stores the result in loaded on line 7. If half of the swf had downloaded, then loaded would be 0.5. To get the load-progress as a percentage, loaded is multiplied by 100, the result is automatically converted to an int and stored in percent.

The text field is updated to show the current load-progress as a percentage. The scaleX property of the loading bar is set to loaded. If loaded were 0.4, the loading bar would be set to 40% its original length.

6
7
8
9
10
11
12
function progressListener(e:ProgressEvent):void {
  var loaded:Number = e.bytesLoaded / e.bytesTotal;
  var percent:int = loaded * 100;
 
  loadingText.text = "Loading: " + percent + "%";
  loadingBar.scaleX = loaded;
}

Finally, when the swf has downloaded, an Event.COMPLETE event will be dispatched, and completeListener() will be called. This listener unregisters itself and progressListener(), before instructing the swf to go to and stop on frame 2. This is usually where the game would begin.

14
15
16
17
18
function completeListener(e:Event):void {
  loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progressListener);
  loaderInfo.removeEventListener(Event.COMPLETE, completeListener);
  gotoAndStop(2);
}

Now that you’ve created the preloader, you’ll need to test it. One way to do this is to create a new layer called “Picture”, and import an image of around 100k to the Stage on frame 2 of that layer. First test the movie as you would normally with CTRL+ENTER. Then, in the window that appears, select View > Download Settings > 56K. Now select View > Simulate Download. If all goes well, you should see the loading bar increase in length and the percentage in the text field increase in sync. Feel free to simulate downloading at different speeds.

Your timeline should look like this:

Timeline state

Feel free to link to our content. However, we do not permit any copying.

18 Responses to “Game preloader”


  1. 1 Inferno

    Well.. Can you help me? I got problem whit scrip lines:
    loadingText.text = “Loading: ” + percent + “%”;
    loadingBar.scaleX = loaded;
    When i start test movie it gives me errors in those lines.
    What should i do? What did i did wrong?
    Please help me!

  2. 2 gAb

    hey i’ve followed your instructions but the swf just go ahead to the 2nd frame…without doing the loading thing…

    help? thx.

  3. 3 gAb

    hi…the preloader works well in the simulation…but…

    1) Is it possible to play transition on second frame? because i tried and it didnt work.
    2)Why does the loading work only in the simulation? in the real swf file it doesnt work at all.

    Please reply to my email asap…thx…

  4. 4 TechnoMono

    @Inferno

    Make sure you’ve given the text field an instance name of “loadingText”, and the loading bar an instance name of “loadingBar”. Forgetting the instance names is the most likely cause of your problem.

    @gAb

    I’m not quite sure what you mean by “play transition on second frame”; do you mean creating a fading animation between the preloader and your game’s start screen?

    You will only see the preloader working if your swf takes time to download; if it was located on a server and was a reasonable size, then you would see the preloader. However, when playing the swf in the standalone Flash player on your own system, you wont see anything because the swf is not being streamed from a server.

  5. 5 gAb

    oh ok…because im doing this preloader for a project in school..so i wont have a server to upload to…

    can i personally request a similar code that does not need server upload to make he preloader work? i’ll be grateful if you would help me..

  6. 6 TechnoMono

    Here’s a simple script that will simulate a download:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    stop();
     
    var startTime:int = 0;
    var bytesToDownload:int = 51200; // 50K
    var downloadSpeed:Number = 10.24; // 10K
    var bytesSoFar:Number = 0;
     
    addEventListener(Event.ENTER_FRAME, enterFrameListener);
     
    function enterFrameListener(e:Event):void {
      var timePassed:int = getTimer() - startTime;
      startTime += timePassed;
     
      bytesSoFar += downloadSpeed * timePassed;
      var loaded:Number = bytesSoFar / bytesToDownload;
      var percent:int = loaded * 100;
     
      loadingText.text = "Loading: " + percent + "%";
      loadingBar.scaleX = loaded;	
     
      if (percent >= 100) {
        removeEventListener(Event.ENTER_FRAME, enterFrameListener);
        gotoAndStop(2);
      }
    }

    You’d place this on frame 1 of your movie. Make sure you create the loading bar and text field as instructed in the tutorial.

    Hope this helps :)

  7. 7 gAb

    Am i able to do a tween after the loading? I can’t seem to do so.

    Thanks a million!

  8. 8 TechnoMono

    @gAb

    You should only have to place your tween animation on frame 2. The movie will move onto frame 2 once the preloader finishes.

  9. 9 gAb

    hmm…then it should be gotoandplay(2) then instead of gotoandstop(2)…

  10. 10 hasra

    i got a small problem, i have followed all the steps here (i think) but it appears no loading text, and the loding bar is not “loading” it only jumps to frame 2

  11. 11 hasra

    nvm, just made it

  12. 12 TechnoMono

    @gAb

    That depends. If you placed an animation on the main timeline starting at frame 2, then you would use gotoAndPlay(2). Usually though, you’d place your game in a movieclip on frame 2 and use gotoAndStop(2).

  13. 13 gAb

    I see…because I’m using the preloader for an interactive poster as a school project, so i think only gotoAndPlay(2) works…

  14. 14 michael

    well if i dont have actionscript 3.0 the EVENT thing wont work?

    Because when i create a new document it says actionscript 2.0 and i dont know how to switch it to 3.0 and when i run this preloader the debugger says

    **Error** Scene=Scene 1, layer=Actions, frame=1:Line 6: The class or interface ‘ProgressEvent’ could not be loaded.
    function progressListener(e:ProgressEvent):void {

    **Error** Scene=Scene 1, layer=Actions, frame=1:Line 8: The class or interface ‘int’ could not be loaded.
    var percent:int = loaded * 100;

    **Error** Scene=Scene 1, layer=Actions, frame=1:Line 14: The class or interface ‘Event’ could not be loaded.
    function completeListener(e:Event):void {

    Total ActionScript Errors: 3 Reported Errors: 3

  15. 15 TechnoMono

    @michael

    Currently only Flash 9 (CS3) supports AS3. This script needs to be complied as AS3; you can not compile it as AS2, hence the errors.

  16. 16 michael

    @TechnoMono

    Well can u find me a link to dl flash 9 for free?

    And even if i get it (i am currently making a game which is really good and difficult to make since i am a new flash programmer) how am i going to compile this game to as3?

    just by opening the existing flash document 2.0 with flash 9 and instantly compiling it?

    Well i also have a question that may seem rediculus to you… how can i add a frame before the 1st frame and how can i add one between 2 frames?

  17. 17 noday1914

    Thanks for the tutorial - everything works perfectly for me the first time … except that when trying to load the movie a second time, my browser simply stops at the first frame, and doesnt go on

    any ideas would be appreciated

  18. 18 mstoy

    Hi! Thanks so much for the pre-loader! It works great, except for when refreshing browser (without emptying my cache).

    After refreshing, it just gets stuck on frame one, with the loader bar. I did switch

    gotoAndStop(2); - to - gotoAndPlay(2);

    but no luck. When I empty the cache, the preloader works - but, again, not if I refresh. Any thoughts?

Comments are currently closed.