Creating a Preloader in ActionScript 3.0 and Flash CS3
- Create necessary variables. You'll need the path to the file you want to load, in the form of a string. You need a URL request to represent the URL of the file, and you'll need an instance of the Loader class to load the file.
- Add event listeners to your Loader object's contentLoaderInfo property to listen for the Event.COMPLETE event (for when the file is done loading) and the ProgressEvent.PROGRESS event (to do stuff while the file is loading, or to show a preloader). You can learn more about the contentLoaderInfo property in Flash Help. Basically, it's the property that holds all of the information about the file that's loading, so you need to use it to register event listeners.
- Create event listener functions to respond to the events. Don't forget to put the loader on the stage using addChild() once it's loaded.
- In the ProgressEvent listener, you can access the loading info via the ProgressEvent's bytesLoaded and bytesTotal properties. Divide bytesLoaded by bytesTotal to calculate the percent that is loaded. The value will be between 0 and 1. Hold it in a variable for easy reference later on.
- To get a number that represents the percent loaded that is between 1 and 100, multiply the percent loaded variable by 100 and round the number using Math.ceil (so you don't get zero as a result).
- Use your rounded percent to refer to a movie clip frame to show when the file is at a particular percent. For example, once your file is 50% loaded, the preloader movie clip will display frame 50.
Labels: ActionScript 3.0, Flash CS3, preloader, source code
