Friday, August 29, 2008

ActionScript 3 packages done right

As a somewhat semi-experienced XHTML/CSS programmer, I made several large mistakes when I started object-oriented programming in AS3. There just isn't much documentation on the basics of AS3 packages and package structure, even in instructional books. So here's my take on it, based on hard experience.

You should start your AS3 programming adventure by creating a high-level directory for all your your classes. I called mine 'Classes'. Now, open up Flash and register this directory so that Flash can find it and use the classes in it. In windows, you can do this by going to Edit>Preferences, clicking on ActionScript in the tab on the side, clicking the button that says 'ActionScript 3 Settings...', and clicking the button with the crosshairs on it. In the dialog box that pops up, find your 'Classes' directory and click 'Ok'. Now, Flash can find your classes!

Say that you're creating an AS3 application for called Flashy Flash App. The tradition would be to create this file structure in your class directory: com>somesite>flashyflashapp. This way, all the classes for that site will be in one central place, separate from all your other sites' classes. In this file, you would create a document class called Here's how you would start the class:

package com.somesite.flashyflashapp {
 public class FlashyFlashApp {
   /* Lots of code goes here */

You should note several key details. First, the file path between package and first bracket is relative to the main class directory. That means, the location of your .fla, flashyflashapp.fla, is completely irrelevant to the package info. Second, note that the class' name exactly matches its filename, including capitalization. If you don't do this, you'll encounter all sorts of nasty errors.

To link the .fla to the document class (the code that starts up the program), type its location into the text box that says 'Document Class' beside it like so:


This, too, is case sensitive, so be very careful with your caps. Now, any code inside the document class,, will execute as soon as the program runs.

If you're like me, you've got a big question right now: "What about once I try to put the finished swf on my site? Won't I have to move all those classes and update all those package definitions?" Luckily for you, the answer is no. Unlike CSS, Javascript, or any of the other web technologies I was comfortable using, all of the required code for a Flash swf to run is in the one central swf. The only part of all this work that you will put on your actual web server is the final swf. Unless your script uses one of AS3's loading classes, like Loader or URLRequest (or whatever), you won't have any problems using just that one small swf.

If you've managed to stay interested this long, I commend you. I hope this post will help at least one person avoid some of the mistakes I made. Thanks for reading!