Quick Tip: How to Use a Document Class in Flash
basix

How to Use a Document Class in Flash

Share

We’re making some changes at Activetuts+. From now on, our tutorials will be using class-based code, instead of timeline code, wherever possible. This Quick Tip explains what you’ll need to know.


Why Use Class Files?

I’ll admit it – sometimes, coding entirely on the timeline is useful. It’s a quick way to test out an effect, and the easiest way to sync actions to specific frames of an animation.

But for any project that relies more on code than on animation, there are serious disadvantages. All your ActionScript is trapped inside the FLA file; you can’t split the programming between different developers, you have to copy and paste code if you want to re-use it, and you’re forced to use Flash’s Actions Panel.

Using class files sets your code free. And it’s really no harder than coding on the timeline; it just involves a little more setup. I’ll walk you through creating a Flash project that uses classes, then break down a class file in detail.

(Part of the reason we’re switching to classes is to make it easier for AS3 developers that don’t use Flash itself to follow our tutorials. If you’re one of them, I expect you’re used to dealing with classes already, but you can always read this Quick Tip as a refresher – just ignore the bits about Flash!)


Step 1: Create a FLA

I’m sure you already know how to do this. Open Flash and click File > New … Flash File (ActionScript 3.0). Save it wherever you like. I’ve called mine Example.fla, but it doesn’t matter what name you choose.


Step 2: Create an ActionScript File

Click File > New … ActionScript File. Save this as Main.as in the same folder as your FLA.

This file is where we’re going to put the code that powers the FLA itself, but how will Flash know how to find it?


Step 3: Link the FLA to the AS File

You may have dozens of AS files in the same folder as the FLA, so Flash won’t want to guess which one to use. We’ll have to tell it.

Switch to the Selection tool (Shortcut: V), then make sure you have nothing selected (hit Ctrl-Shift-A). Open the Properties panel (Window > Properties).

If you’re using Flash CS3, it’ll look like this:

Flash CS3 Properties Panel

Enter Main in the box labeled “Document class” – that’s to match the name of your ActionScript file, minus the “.as” file extension..

If you’re using Flash CS4, it’ll look like this:

Flash CS4 Properties Panel

In this case, you’ll need to enter Main in the box labeled “Class”. For some reason, Adobe dropped the “Document” bit.


Step 4: (Optional) Reorganize your Folder Structure

You don’t have to keep all your files in the same directory. Check out this Quick Tip screencast if you’d like to know how to move things around.


Step 5: Write your Document Class

Open your Main.as file and paste the following code:

package
{
	import flash.display.MovieClip;
	public class Main extends MovieClip
	{
		public function Main()
		{

		}
	}
}

This is a basic empty document class. It’s the smallest amount of code we can write that will actually run. Let me break it down:

The package keyword tells Flash that all of the code between its curly braces is part of a single group.

The package keyword tells Flash that all of the code between its curly braces is part of a single group.

The class keyword groups functions and variables together.

Writing class Main also groups code together, but in a different way. Classes contain functions and variables; packages contain classes and import statements.

Note: you have to give your class the same name as the AS file: Main.

What about public? Well, that just means that other classes in your code will be able to see this class.

We want our class to extend the functionality of a regular MovieClip - hence, 'class Main extends MovieClip'.

This class Main is going to power our FLA. By default, our FLA is a movie clip (it has a timeline).

We want Main to be able to do everything that a movie clip can do, plus more based on the code that we write. In other words, we want to extend the functionality of a regular MovieClip.

(Sometimes, we might not need to do any animation on the stage’s main timeline; in this case, we don’t need to extend MovieClip, and we can just extend Sprite instead. MovieClip itself extends Sprite, but adds extra features for animation, like the nextFrame() function. So if you’re not sure whether you should extend MovieClip or Sprite, go for MovieClip — it’s safer!)

The 'import' line tells Flash where to find the actual MovieClip so that we can extend it.

MovieClip is itself a class.

Flash doesn’t automatically keep track of where all its class files are stored; in order for our extends MovieClip code to work, we need to tell Flash where to find the MovieClip class. That’s what the import line does.

Import statements always go inside the package and outside the class, at the top.

Every class contains a function with the same name as the class. The code inside it is run when an object of this type of class is created - in our case, when the SWF is loaded.

Every class contains a function with the same name as the class. It’s called the constructor function.

All the code inside this function is run when an object of this type of class is created – in our case, code between these curly braces will be run when the SWF is loaded.

Don’t worry if you feel you don’t quite grasp all of this yet. Once you start actually using classes and writing your own, it’ll all snap into place.


Step 6: Make it do Something

As I said in Step 5, the constructor function contains the very first code to be run when your SWF is loaded. So let’s put something in there to make sure everything’s working:

package
{
	import flash.display.MovieClip;
	public class Main extends MovieClip
	{
		public function Main()
		{
			trace( "Yep, it's working" );
		}
	}
}

Line 8 is the only new one there. Test your SWF in the usual way (Control > Test Movie). If all’s well, you should see “Yep, it’s working” pop up in the Output panel. If not…

  • Have you saved the change you made to Main.as?
  • Is your FLA’s Document Class set to Main?
  • Are you definitely testing the Example.fla movie?

If none of these questions help, please post a comment.


Step 7: Try Something a Little More Complex

Try replacing your Main.as code with this:

package
{
	import flash.display.MovieClip;
	public class Main extends MovieClip
	{
		public function Main()
		{
			var greeting:String = "Hello";
			trace( greeting );
		}
	}
}

Simple, right? We’ve just created a new String variable inside the constructor function. Now let’s add a new function:

package
{
	import flash.display.MovieClip;
	public class Main extends MovieClip
	{
		public function Main()
		{
			var greeting:String = "Hello";
			changeGreetingToFrench();
			trace( greeting );
		}

		public function changeGreetingToFrench():void
		{
			greeting = "Bonjour";
		}
	}
}

There are a few things to note here.

Firstly, the new function goes inside the class, and after the constructor – by convention, the constructor is the first function in the class.

Secondly, the new function is public; when coding inside a class (and not on the timeline) it’s good practice to put “public” (or “private” or “protected”, but I’ll leave those for another post) at the start of the line that defines the function. It’s just a way of letting other classes know whether or not they can access it.

Thirdly, the new function’s definition ends with :void. This just means it doesn’t return a value. Constructor functions don’t need the :void because they can’t return a value.

If you test this movie, you’ll get an error message:

Main.as, Line 15: 1120: Access of undefined property greeting.

When you create a variable inside a function, it can’t be accessed by other functions. If you want every function in the class to be able to access the variable, you need to declare it inside the class but outside all of the functions:

package
{
	import flash.display.MovieClip;
	public class Main extends MovieClip
	{
		public var greeting:String = "Hello";

		public function Main()
		{
			changeGreetingToFrench();
			trace( greeting );
		}

		public function changeGreetingToFrench():void
		{
			greeting = "Bonjour";
		}
	}
}

Just as with functions, if you declare a variable outside of a function, you need to start it with “public” (or “private” or “protected”). Unlike functions, variables should be defined above the constructor.

Test your movie now and you should finally get a nice greeting in French. How useful!


Wrapping Up

So, this is not exactly an exciting result, but hopefully you now feel able to follow tutorials that don’t code on the timeline.

I really want to make sure everyone understands how to use a document class, so please, if any of this was unclear, post a note in the comments. Once we’ve sorted out the confusion, I’ll edit the Quick Tip to make it easier for the next person to understand. Thanks :)

Related Posts

Add Comment

Discussion 61 Comments

Comment Page 2 of 2 1 2
  1. Peter says:

    One of the better and easy to understand explanations about document classes!

  2. J Sacco says:

    Excellent tutorial

    Nice guide towards OOP AS3

  3. André says:

    It´s one of the biggest difficulties of who are starting in AS3, it´s a great explanation and i am sure that people will understand very easily!

  4. ruairi says:

    Excellent article, a very straightforward and clear explanation.

  5. Felix says:

    I know I should be doing this, but it’s just so simple to just create a new document, press F9 and start typing… I will try to force myself to do it on my next project!

  6. Hi Michael, I agree totally, we have to this carry on the next level. Excellent guide.

  7. André says:

    I will give a tip for who want to create an animation and still use the Document class or classes for each object…

    When you press F9 and create your code there, let´s say you coded at frame 8 for example, you can do this also in Document class, there is a function of MovieClip class that isnt documented, addFrameScript, this allows to create a function when the animations reaches that frame, BUT the first frame on animation is frame 1, but in addFrameScript is frame 0, so this way if we want to code something for frame 8 for example we need to use the number 7 as reference… example:

    public function Main():void{
    addFrameScript(7,myScript);
    }

    private function myScript():void{
    trace(currentFrame); //will return 8
    stop();
    }

  8. Cadin says:

    Wow, this is the clearest and simplest explanation I’ve seen.
    This will be a great resource for anyone just getting started with class files.
    Nice work Michael.

  9. Thanks for the feedback, everyone! Glad people are finding this clear :)

  10. nicolas says:

    Wish I had stumble upon this a couple of months ago… Would be really appreciated to have a tutorial (or quick tip) about inheritence and all other concept of OOP (in the same easy way..)

    Thanks a lot !

  11. Web 2.0 says:

    Can we embed PDF in Flash?

  12. Djinn says:

    Great tut! Thanks … i’ve just started in flash and i really like your tutorial. thx again .. and good work

  13. Rainui says:

    Hi, long time viewer, first time poster.

    Before I start, AWESOME tut Michael! I appreciate the time and effort you made on this guide.

    Now to be honest with everyone, this was the first and only tut I could actually follow. I’ve been using flash for almost 4years now and I still don’t understand the basics of action scripting. Just when I thought I was starting to get my head around basic (and I mean BASIC) AS2, everyone switched to AS3, and just to top it off, people are making class files of it.

    Please Michael, if you or anyone one else, can write a tut as simple and straight forward as yours (without the technical jargon) about the basics of AS3, how/when/where and why to use it, and maybe have some simple examples that we can follow or write ourselves.

    I know this is probably a lot to ask, but with all the tuts out there on the net, you guys here so far seem to just make sense!

    Thanks a lot in advance!

  14. viaria says:

    extends Sprite better, and enough basic tips..

    • I disagree. What if you’re using the Flash authoring environment, and you want to use the three-frame preloading method? You’ll need the doc class to have a timeline — which means you’ll need it to extend MovieClip.

      And since MovieClip extends Sprite, we don’t really lose anything this way, except maybe a tiny bit of performance. Overall, it’s more flexible to extend MovieClip.

      We won’t be stopping the basic tips any time soon, but part of the aim of this Quick Tip is to let us post more advanced tutorials.

      Cheers for your comment!

    • André says:

      It´s a convention extend the Sprite class when we dont have timeline animation, it´s a good habbit, but it´s not an obrigation…

      Personally i extend MovieClip only when i have timeline animation… but most time i extend the Sprite class, since i use few timeline animation

  15. Konstantin says:

    Thank you for this great site and these excellent tutorials, I don’t mean only this one of course :-) .

    Michael, it’s a very good idea to start making tutorials based on classes from now on.

    Unfortunately, to understand classes, interfaces and other stuff better these tutorials won’t be enough.
    I’d recomend to read Colin Moock’s Essential Actionscript, especially chapters 1 to 7

  16. sven says:

    Very nice Tut !

  17. Ngộ Độc says:

    very easy and nice tuts, thanks michael, thanks tutplus !

  18. smecking says:

    Thanks Michael.

    Very good tut – thank you!

    My question is when you setup your main.fla with the Main Document class, how do you layout your site for all your other items. (ie. preloader, nav, other pages). For instance, I have a preloader.fla (nothing on the timeline – but movieclips in the library) using Preloader.as as its document class How do I connect it to the main.as? If I instansiate it (say myPreloader:Preloader = new Preloader()) in the main.as file, I lose the MovieClips in the Preloader.fla.

    I hope this makes sense. If you know of a post or the answer, I would really appreciate it.

    Thanks1

    • Hey smecking,

      I’m a little confused as to what you’re asking. What do you mean by you “lose the MovieClips in the Preloader.fla”?

      • smecking says:

        Hi Michael,

        Thanks for the quick reply and I apologize for the confusing post and should have worded it differently.

        -Say I have a main.fla using Main.as for it’s Document class and a menu added to the main stage by coding it in the Main.as file.

        -I have then created a “contactpage” as a separate .fla file. The contactpage .fla has a number of items in it’s library (ie. background gradient, text, pictures,movieclips, etc.) The document class for the contact page is Contact.as which has code to input text..

        - If I wanted to make it so I could bring up the contact page through the main.fla’s menu, how would I load it?

        –>I couldn’t use var myContactPage:Contact = new Contact() b/c it would only load the class and not the contactpage.swf (losing the items in it’s library).

        –>Is it good practice to just use the loader to load the ContactPage?

        –>Or, do I convert contactpage into a movieclip and place it in the main.fla library to access all it’s items?

        I hope this makes more sense. Essentially what I’m asking is when building a website with main.fla and document class Main.as. If you have multiple pages (ie.gallery, contact, home, etc.), what is the best way to access those other pages from main?

      • Ah, I see what you’re asking now. Good question.

        You could compile the contactpage.fla into a SWF, then load that contactpage.swf into your Main FLA at runtime using a Loader.

        You could compile the contactpage.fla into a SWC, and add it to the library. This would let you access all the internal properties and functions of your Contact class, but it’s a little more complicated than I can explain in this comment. (If you’re interested, I’ll get a Quick Tip written on how to do that.)

        Probably the most convenient thing to do is to copy everything into Main’s library, and (as you suggested) have a MovieClip called Contact which is linked to the Contact class in Contact.as. Then you’ll keep all the items in the library, and have access to all the properties and functions. (Are you familiar with linking library symbols to classes?)

        The issue with that is, all your pages are in the same FLA; if you want to re-use, say, the gallery on another website, you’ve got to copy and paste it out of your Main FLA, and that will get messy.

        Does that make sense?

  19. ArunRaj says:

    too gud Sir!!

    i have no idea wat is document clas and AS3 before reading ur tuts !! great job sir !!

    thx for that

    ArunRaj
    INDIA

  20. John Doe says:

    This is a noob question but how do you know what you will need to import into your class?
    Is there a wildcard * option to use for testing?

    • Actually I think that’s a good question.

      You have to import almost all classes; the exceptions are the “top level” classes, which are listed here (scroll down).

      For every other class, if you refer to it, you’ll need to import it. For example, here we referred to MovieClip in “extends MovieClip”, so we have to “import flash.display.MovieClip”.

      Think of it this way: inside Flash there are a bunch of class files like TextField.as and MovieClip.as. These are stored in the folders “\flash\text\TextField.as” and “\flash\display\MovieClip.as”. When you write “import flash.display.MovieClip”, you’re telling Flash to grab the MovieClip.as file from the “\flash\display\” folder so it can be used later.

      How do you know which classes are in which folders? You have to look it up! There’s a list of all the classes built in to AS3 here, along with the package that you’ll need to import.

      (So technically you don’t need to import classes at all — you could write “extends flash.display.MovieClip” and “myMovieClip = new flash.display.MovieClip()” and so on — importing just lets you use the short version.)

      Most AS3 editors (apart from the one in Flash itself) will automatically write an import statement when you refer to a class. For example, I use FlashDevelop to write all my class files, so if I type, for example, “var someTextField:TextField = new TextField()”, it’ll automatically put a “import flash.text.TextField” at the top of my code. Very useful.

      Finally, yes, you can use a *, but only within a folder. So you can write “import flash.display.*” and it’ll import all of these classes, but you can’t write “import *”.

      Hope that helps!

  21. John says:

    Yea that does help. Thanks for clearing that up for me and thanks for replying to the question.

    Just an idea for the development team, it would be nice to have a notification option such as the one on actionscript.org so you wouldn’t have to come back and check on a comment. I think that would encourage interaction.

  22. Durgesh says:

    really great & simple to understand . can you post some more basic tutorial on oop concept.

  23. Juan says:

    Thank you for the Tutorial it really made things more easier.

  24. rock lobster says:

    whats the next step to this? Will there be a tutorial for linking classes to e.g. an animation or textfields?
    Anyway thanks for a nice intro to classes.

  25. Eli McMakin says:

    Good stuff. I really like AS3s language. I am just now learning PHP OOP, and it does not seem as strongly typed. Also, I might be biased, but the code is uglier in PHP.

  26. Lewis Cowles says:

    I liked the tutorial, I cannot dispute it’s simplicity etc however you had scope of variables and did not really cover that too well

    For those of using flex this is the simplest non-mxml as3 to create a functioning flash movie based on MovieClip

    # import flash.display.MovieClip;
    # public class Main extends MovieClip
    # {
    # public function Main()
    # {
    # //Add some code here
    # }
    # }

    also as a footnote you could either opt for component based swf authoring with different classes (one .as file per class) or a modular set of applications that are loaded into a main environment, I myself prefer the latter for larger apps because it saves on the memory footprint of the flashplayer and you can then use php, webserver etc to do clever things like authentication, maybe i’ll post a tutorial here soon

  27. Hem Singh says:

    but if I have to use this document class for child level MovieClips which are not on frame one, how I will do it

  28. mack says:

    how do u link the fla to the .as file. i have set up the flash file and all of my files are inside the same folder but for some reason nothing is happening

    • Odd… have you set the Class (or Document Class) attribute? When you click the pencil next to that box, what appears?

      • Olaf Mayer says:

        Hi there,

        I do have the same problem. I have set up both files, the .as and the .fla. I have left the .fla file empty and typed the name of the .as file into the class field (I am using CS4).

        If I am testing the .fla i can not see any output, despite the fact, that it is definitely linked to the .as file, as I can tell by clicking on to the pencil next to the class field and it will open the .as file with the code in it. I do not have any syntax errors in my .as file either?

        I can’t explain it, and I have looked at different tutorials on the web to get a hint why it is not working, but haven’t had any luck yet.

        I really want to get it working, before moving on to the next tutorial.

        If you have any further tips, it would be highly appreciated.

        Kind Regards,

        Olaf

      • Hey Olaf,

        I’m stumped. It sounds like you’re doing everything right.

        Would you like to upload a zip with your FLA and AS files to a site like FileFactory so I can take a look?

      • Olaf Mayer says:

        Hi Michael,

        thank yo, but I worked the problem out myself in the end. It was just down to my file organization. I starting working in a different folder then I finished. So I copied all the files into the same folder and saved them under a new name and all of a sudden it worked!

        cheers,

        Olaf

  29. Bhavuk Vij says:

    Hi,

    What actually is document class. Why we use it?? Is it just to associate stage with class..

  30. pixelBender67 says:

    Nice and easy now can we do a full blown website with full screen capabilities , liquid layout, with an xml driven slide show and how to load multiple .swf files ? I am trying to build a portfolio site and only know how to do it on the time line, also I want to make it connect to my HTML site if the user does not have flash enabled. like the people on the i-phone ? That would be awesome :)
    Great tut !

  31. Dustin says:

    Great tut. Thx a lot!

  32. yatin says:

    Hi, It is a great tutorial explanation, everything is clear no doubt. Thanks a ton for making it so simple to understand.

  33. Loganb says:

    Thanks for the tutorial. As and artist who dabbles in code, ever since as 3.0 came along I felt “shut out” by the leap in complexity. This Tutorial explains things very well.

    one Question: I’m trying to take an FLA with action script embedded in a timeline and make seperate the .FLA and .AS . Just wrapping it all in inside of the Main() function and importing MovieClip doesn’t accomplish this: It seems to be missing crucial classes (Mouse events in my case).

    My Question is: Does embedding the action script in the timeline implicitly import a bunch of ‘default’ class packages, where as external .as files must explicitly import them?

    • Cheers :)

      You’re right, the IDE implicitly imports some classes. I’m afraid I don’t know which these are, so you’ll have to figure it out from the error messages.

      Hope that helps!

  34. konvivial says:

    hey!! Nice Tutorial

    I have few queries.

    1. Can we use custom class along with document class.?
    And if yes then please let me know how to do that.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.