By Dan Carr
 
Created
8 June 2010
 

Requirements

 
Prerequisite knowledge

This article is geared toward both designers and programmers working in Flash Professional CS5 and later. The article assumes that you have a basic understanding of the Flash Professional user interface. You'll also want to have some experience with the ActionScript 3 syntax to get the most out of the code debugging sections.
 

 
User level

Intermediate
 

 
Required products

Debugging is the process of removing known issues from your application or testing for unknown errors and performance problems. In the end, this process is usually what makes or breaks a project. This article is designed to help you understand the debugging process and issues common to developing in the ActionScript 3 environment in Adobe Flash Professional CS5.
 
The topics and workflow suggestions in this article are organized for both designers and developers. Your goal along the way will be to identify and interpret issues, to get comfortable with the process of working with errors, and to define a workflow for resolving errors when they occur. You'll work in Flash Professional CS5 and take a look at the new integration with Adobe Flash Builder 4 as well.
 
Note: If you are still using Flash CS4, refer to the previous version of this article: Understanding ActionScript 3 debugging in Flash CS4 Professional.
 
To help you visualize the process, I have provided a series of sample files, each of which contains a broken version and a fixed version. The fixed versions are supplied for reference, but you'll be able to walk through the solutions during the course of the article.
 

 
What's an error and why does it keep following me?

One of the first things I noticed when I started working in ActionScript 3 is that it's far less forgiving than ActionScript 2 when it comes to output errors. Ultimately, this is a good thing, which I've become used to and even use to my advantage. But it's a different experience than working in ActionScript 2, that's for sure.
 
This section is intended to give you a broad overview of the types of Adobe Flash Player issues you'll deal with and how they are visualized in the Flash Professional workspace.
 
 
Understanding the ActionScript 3 environment
The ActionScript 3 architecture runs on a new engine (ActionScript Virtual Machine 2) which removes many of the legacy issues that have accumulated in previous versions of Adobe Flash. The update is dramatic enough that it requires a new file format that can be viewed in Flash Player 9 and later.
 
For a technical overview of the new ActionScript engine, please read the following paper:
 
In Flash Professional CS5, the ActionScript 3 environment exists in two parts: the ActionScript 3 FLA file and the ActionScript 3 programming language.
 
By default you're working with an ActionScript 3 FLA file when you create a new file in Flash Professional. The look of the elements in the file and the general experience is the same as it is with an ActionScript 2 FLA file, but the Flash Professional workspace updates to show ActionScript 3 features when an ActionScript 3 FLA is in focus. Most notably, you'll see that the set of components is different in the Components panel.
 
When working with an ActionScript 3 FLA file, managing assets and creating symbols is pretty much the same process that you're used to in ActionScript 2, but the rules for coding change a bit. Code can be added to keyframes along your timelines or linked to the main timeline or your symbols using external ActionScript files. (Code can no longer be attached to instances on the Stage.)
 
When you publish your movie, the ActionScript code is compiled into the resulting SWF file. The ActionScript 3 compiler processes the ActionScript code by checking to make sure that the structure of the code and code assignment all match the strict rules of the ActionScript 3 language.
 
More often than not, you'll deal with errors at compile time whenever you publish the movie.
 
 
Understanding what an error is
Errors are notifications built into the ActionScript language and compiler process. Errors come in three flavors: compiler errors, runtime errors (ActionScript exceptions or error events), and warnings:
 
Compiler errors are generated when the file is published and the ActionScript is compiled into a SWF file. Compiler errors enforce rules that allow the ActionScript code to run in an optimal and expected way. When compiler errors appear, the SWF file will fail to export until the errors are removed.
 
Runtime errors are generated by ActionScript objects when issues arise after compile time, during playback. Runtime errors come in the form of error events or ActionScript exceptions containing error description objects. Flash Player tries to ignore runtime errors, letting them fail silently in the background, but if a fatal error occurs, it will flood the Output panel with messages and stop the playback of the movie.
 
Warnings appear at compile time, but generally don't stop the export or playback of the movie.
 
 
How to interpret errors and warnings
The first step is to understand the type of visual feedback you'll see in Flash Professional. Errors will present themselves in one of two ways in the workspace:
 
  • Output panel
  • Compiler Errors panel
The Output panel and Compiler Errors panel both appear in the Flash Professional workspace. I usually group the two panels together and drag them off to the side on a second monitor. My expectation is that I will see compiler errors and my own trace action output consistently as I develop, so I make sure that I put the panels where I can see them without being distracted.
 
Once you see error feedback in one of these forms, you'll want to make sure to pause and read the related error text. The text may seem cryptic, but there's usually enough of a clue to point you in the right direction. Also, take a moment to observe where you are in the timing of the file. An important part of bug reporting and debugging is being able to define the problem and the steps leading up to it accurately.
 
 
Compiler errors
Compiler errors are often easier to deal with than runtime errors as they can be seen clearly during publishing with line numbers pointing to the source of the issue. Compiler errors occur while the ActionScript code is being compiled into the SWF file. This happens when you run the Test Movie or the Publish command (see Figure 1).
 
A compiler error visible in the Compiler Errors panel in Flash Professional CS5
Figure 1. A compiler error visible in the Compiler Errors panel in Flash Professional CS5
Please see Compiler Errors in the ActionScript 3 Reference for the Adobe Flash Platform for a full list of error types.
 
 
Runtime errors
Runtime errors occur while the published SWF file is running in the debug player, the standalone player, or the ActiveX player (see Figure 2). Runtime errors occur commonly as a way to notify you when something isn't right in your application. If you leave these unhandled, the Flash Player tries to allow the script to fail silently, but may pause the playback of the SWF file, causing unpredictable visual results.
 
A runtime error visible in the Output panel in Flash Professional CS5
Figure 2. A runtime error visible in the Output panel in Flash Professional CS5
Please see Runtime Errors in the ActionScript 3 Reference for the Adobe Flash Platform for more information. Also see Basics of error handling in the ActionScript 3 Developer’s Guide for a further breakdown of runtime error concepts
 
 
Warnings
Warnings appear when you publish the SWF as a way of telling you something is breaking a rule in ActionScript, but it's not severe enough to cause an error (see Figure 3). I mostly see warnings for duplicate variable names and migration issues with older content.
 
A warning message visible in the Output panel in Flash CS4
Figure 3. A warning message visible in the Output panel in Flash CS4
Please see Compiler Warnings in the ActionScript 3 Reference for the Adobe Flash Platform for more information.
 
 
Performance issues
While technically unrelated to ActionScript errors and compiler errors, assessing performance and dealing with performance issues is part of the debugging process. This topic affects both designers and programmers even though they may look at it from different perspectives.
 
Common performance issues include:
 
  • Overloading movie clips in the Flash Player
  • Vectors usage and bitmap caching
  • Hardware acceleration in Flash Player 9 and 10
  • Content loading and garbage collection
The most common way to overload a SWF file is to use too many movie clips or too many overlapping animated vectors. Movie clip efficiency has been improved in ActionScript 3 to allow the use of hundreds of movie clips at any given time, but I find in my own work that overloading vector graphics can force the player to stutter during playback. Usually, the solution comes down to identifying issues with the way graphics are overlapping, the size and number of animations on the screen, and the level of opacity being used. Simplifying the content and using the BitmapData class or the bitmap caching features of Flash Player to add raster optimizations can help improve performance.
 
Another area I'm seeing performance issues is in using the Flash Player hardware acceleration features with full-screen rendering. Newer computers—and computers set up for HD video playback—are generally going to handle hardware acceleration well. However, computers with older video cards may experience issues related to the way that Flash Player utilizes the computer's video hardware for image scaling. Symptoms may appear as graphic distortions, screen freezes, or variations in frame rate while in full-screen mode. The workaround on the user's end is to turn off the hardware acceleration feature in the Flash Player Settings dialog box.
 
For more information on issues related to hardware acceleration, see Tinic Uro's blog entry explaining some of these problems.
 
One last thing to mention is the issue of content loading and caching. Flash Player uses garbage collection routines that may cause problems when trying to unload content. Garbage collection is the process in Flash Player wherein content that is no longer in use is released from memory. The hitch is that Flash Player considers content to be in use if there are still references to it. This can affect media such as sound, video, and content in nested SWF files. For example, in some cases, you'll try to unload a SWF file that has a sound or video playing and the sound won't stop, even after the SWF file appears to be removed from the screen. The solution to such a problem is to try to stop the sound before unloading the SWF file, or to use the unloadAndStop API available in the Loader object (Flash Player 10 or later). The unloadAndStop command forces Flash Player to remove the media from memory when unloading the SWF file.
 
Garbage collection affects the performance of your application. As a best practice, you should remove all references to an object before trying to delete it. This includes removing all event listeners assigned to the object.
 
 
Flash Player bugs
The Flash Player team is constantly improving the features, performance, and security of the Flash Player. From time to time Flash Player bugs and known issues do arise. Your best bet for handling these situations is to develop a process for identifying and documenting bugs so that you can distinguish between problems in your files or larger issues with the Flash Player. Once I've identified an issue, I usually search through the community for related posts. If other people are hitting the issue and seem to be at a dead end, then I start looking for official Adobe tech notes or bug reports.
 
If you can identify that you're hitting a known issue in the player, usually your best option is to search for a workaround or handle the problem as a documentation issue. In most cases, bugs are worked out as the Flash Player incrementally cycles through its version updates.
 
Check out the article, Introducing the Flash Player bug and issue management system, for more information on searching for existing bugs and reporting new ones.
 

 
Debugging tips for designers

While I spend most of my time writing ActionScript code in a text editor, all my ActionScript files are tied to an ActionScript 3 FLA file and document library. The beginning of every project starts by dealing with graphics production and organizing assets in my Library. So, depending on what task I'm performing, my job title switches between ActionScript programmer and user interface designer.
 
I have found there are a number of issues to be aware of when debugging ActionScript 3 FLA files from the UI designer's perspective. In most cases your main goal will be to understand the expectations of the ActionScript 3 environment and where code must be placed. Also, dealing with migration issues is a common task while upgrading files from ActionScript 1/2 to ActionScript 3.
 
This section provides an overview of the types of issues you'll deal with while working in assets in ActionScript 3 FLA files, with a focus on handling migration issues from earlier versions of ActionScript.
 
 
Common issues designers encounter
The role of the designer is usually focused more on asset management and FLA file production than in complex coding syntax. Still, a designer deals with a handful of programming requirements and concepts that require a certain amount of code-related knowledge.
 
The most common issues you'll see from the design perspective include:
 
  • Code placement errors
    • Code can no longer be placed on instances
  • Errors related to buttons and movie clips
    • Missing instance names
    • Misspelled instance names
    • Instance name collisions with frame script variable names
    • Event handling code in wrong location
  • Errors related to text fields
    • The Variable field is no longer supported
    • The URL field is no longer supported
  • Errors related to components
    • Loading errors with the UILoader and FLVPlayback components
    • Video errors with the FLVPlayback component
  • Errors related to ActionScript assignment
    • Availability of imported classes
    • Missing variable declarations, name collisions, and data type issues
    • Symbol linkage has been replaced by the Class fields in the symbol properties
  • Performance issues
  • Migration issues from earlier versions of ActionScript
 
Changes in ActionScript 3
The ActionScript 3 environment standardizes all coding workflows and, by doing so, removes many of the inconsistencies of prior versions of ActionScript. Ultimately, this is a good thing; but it does present some changes in the way you may be used to setting up your FLA files.
 
The most significant changes from the designer's perspective include the following:
 
  • Code can no longer be placed on movie clip or button instances. All code placement in ActionScript 3 must occur on keyframes along a timeline (called a frame script) or in an external ActionScript file (called an ActionScript class).
  • The event handling structure has been updated. This affects how you handle your button and movie clip code. Assigning event handler functions to buttons and movie clips has changed. You can no longer attach code to an instance on the Stage. Instead, you will use the addEventListener method to assign listeners to all objects in a consistent way. (The benefits of this may not seem immediately apparent, but it's a far more flexible system.)
  • Working with timelines visually in the Flash CS5 workspace is basically the same as before, but ActionScript 3 programming now conceptualizes timelines as display lists. If you're handling instances in ActionScript, you need to be aware of the timing and use of the display list.
  • Symbol linkage no longer exists in ActionScript 3. Symbol properties now accept a unique class name (or class reference) for identification. You can assign ActionScript classes to a symbol in its Symbol Properties dialog box. You may also assign an ActionScript class to the Document class field associated with the main timeline's Stage properties.
 
Debugging tools
Flash Professional CS5 provides a handful of tools which you can use to manage your file assets and search for problem areas:
 
  • Flash Professional workspace, Actions panel, and trace actions
  • Movie Explorer panel
  • Debug Console, Variables panel, and Debug menu
  • Test Movie command and the Bandwidth Profiler
Use the Flash Professional workspace to explore the file. You can search for assets using the Movie Explorer panel (see Figure 4). You can use the debugging panels to track down issues with ActionScript variables and functions.
 
 Movie Explorer panel provides a quick way to search for assets and code placement; it's particularly useful when migrating older FLA files to ActionScript 3 format
Figure 4. Movie Explorer panel provides a quick way to search for assets and code placement; it's particularly useful when migrating older FLA files to ActionScript 3 format
The fastest way to preview your work and check for errors and warnings is to use the Control > Test Movie command. When the SWF file appears in the debug panel, you can select the View > Bandwidth Profiler option to see an overview of the SWF file's profile information (see Figure 5).
 
Bandwidth Profiler available in the View menu when you use Test Movie
Figure 5. Bandwidth Profiler available in the View menu when you use Test Movie
Tip: The Simulate Download and Simulate Streaming options, also available in the SWF file's View menu, tend to be inaccurate. It's best to do your benchmark testing with the files running live on your server.
 
 
Debugging workflow
Working through bugs and issues with your file is a part of everyday life as a designer. It's best if you have an organized approach in place and plan time in your schedule for working through problems.
 
A common workflow from the design perspective might include:
 
  1. Identify the issue (what is it?).
  2. Find the source of the issue (where is it?).
  3. Look up related documentation and define options for solutions.
  4. Rebuild the problem area in a separate file if needed.
  5. Apply the solution and test the work (use Test Movie and the bandwidth profiler).
Tip: I find that it's faster to solve problems in a fresh file than it is to struggle with details in a fully developed project. Once you define a problem, get a sample to work in a separate file and then integrate the working solution back into your project.
 

 
Debugging samples for designers

The following samples will guide you through a normal workflow when migrating your files from ActionScript 1 or 2 to ActionScript 3 format. The supplied files contain ActionScript 2 versions of each sample along with ActionScript 3 in the solutions folder.
 
These steps will walk you through the process of migrating each ActionScript 2 FLA file into the ActionScript 3 format. Along the way you'll see errors, find their sources, and resolve the issues.
 
Follow these steps to get started:
 
  1. Download the as3_debugging_issues_cs5.zip file from the introduction page if you haven't already done so.
  2. Unzip the file to a location on your desktop. You'll be asked to open certain supplied files in the steps to follow.
  3. You can open the completed files from the solutions folder if you'd like the reference.
 
Sample 1: Migrating variables
The ActionScript 3 environment requires that you use the var keyword to declare all variable instances, even on a timeline. This is a simple idea, but it wasn't a requirement in prior versions of ActionScript.
 
Beyond adding the var keyword, this sample shows you how to handle data typing and the new way to reference the root and stage objects.
 
Follow these steps to update an ActionScript 2 file containing outdated frame code:
 
  1. Open the designer_sample1.fla file in Flash Professional CS5.
  2. Run Test Movie to view the working ActionScript 2 file. Notice that the code on the main timeline simply distorts the image and places it in the center of the Stage.
  3. Close the SWF file.
  4. Convert the file to the ActionScript 3 format by choosing File > Publish Settings. In the Publish Settings dialog box, click the Flash tab and switch the Script menu to ActionScript 3. Click OK.
  5. Run Test Movie again. Notice that a compiler error and several warnings are shown in the Compiler Errors panel, and the SWF file fails to load:
Symbol 'Circle', Layer 'actions', Frame 1, Line 2 1120: Access of undefined property _root.
  1. The first thing to do is to fix the reference to _root that generates the first error. You can see from the Location field that the source is located in the timeline of the Circle symbol on line 2. Double-click the Circle instance on the Stage to enter its timeline and select the actions keyframe on the first frame of the timeline. While you could try to use a reference to root or parent, this approach really doesn't work that well in ActionScript 3. It would be better to set the instance's alpha property from the main timeline code where its size and location are set. Comment out or remove the code on line 2 and return to the main timeline.
  2. Go down the line of errors and warnings still remaining. Select the actions keyframe on the main timeline. Movie clip properties no longer start with an underscore (_) in ActionScript 3. Remove the underbars in front of the x, y, width, and height properties.
  3. Run Test Movie again. Notice that a new set of errors appears in the Compiler Errors panel. This time you can see that there are two more issues to resolve. First, each variable on the timeline needs to be declared using the var keyword. Second, the reference to Stage height and width is no longer formatted correctly for ActionScript 3:
Scene 1, Layer 'actions', Frame 1, Line 2 1120: Access of undefined property ovalWidth. Scene 1, Layer 'actions', Frame 1, Line 3 1120: Access of undefined property ovalHeight. Scene 1, Layer 'actions', Frame 1, Line 4 1120: Access of undefined property ovalAlpha. Scene 1, Layer 'actions', Frame 1, Line 7 1120: Access of undefined property ovalWidth. Scene 1, Layer 'actions', Frame 1, Line 8 1120: Access of undefined property ovalHeight. Scene 1, Layer 'actions', Frame 1, Line 9 1119: Access of possibly undefined property width through a reference with static type Class. Scene 1, Layer 'actions', Frame 1, Line 9 1120: Access of undefined property ovalWidth. Scene 1, Layer 'actions', Frame 1, Line 10 1119: Access of possibly undefined property height through a reference with static type Class. Scene 1, Layer 'actions', Frame 1, Line 10 1120: Access of undefined property ovalHeight. Scene 1, Layer 'actions', Frame 1, Line 11 1120: Access of undefined property ovalAlpha.
  1. Update the code to match the following:
// Settings var ovalWidth:Number = 400; var ovalHeight:Number = 100; var ovalAlpha:Number = .5; // Notice that alpha ranges from 0 to 1 // Set size circle_mc.width = ovalWidth; circle_mc.height = ovalHeight; circle_mc.x = (stage.stageWidth - ovalWidth) / 2; circle_mc.y = (stage.stageHeight - ovalHeight) / 2; circle_mc.alpha = ovalAlpha;
  1. Run Test Movie again. Notice that no more errors occur. You were able to successfully update the file to ActionScript 3 syntax.
 
Sample 2: Migrating button and movie clip code placement
It was common prior to ActionScript 3 to place button event-handling code and movie clip event-handling code directly onto the instance you wanted to affect. The problem with this approach is that the code tends to be hard to find and it's spread out across multiple objects.
 
ActionScript 3 resolves the issue by making it illegal to place code on object instances. This concept is pretty simple, but it presents a challenge if you're updating an older file or just trying to get your head wrapped around the ActionScript 3 environment.
 
Follow these steps to update an ActionScript 2 file containing code attached to instances:
 
  1. Open the designer_sample2.fla file in Flash Professional CS5.
  2. Run Test Movie to view the working ActionScript 2 file. Notice that you can start and stop the circle animation by clicking the two buttons.
  3. Close the SWF file.
  4. Convert the file to the ActionScript 3 format by choosing File > Publish Settings. In the Publish Settings dialog box, click the Flash tab and switch the Script menu to ActionScript 3. Click OK.
  5. Run Test Movie again. Notice that warnings appear in the Output panel:
Warning: Actions on button or MovieClip instances are not supported in ActionScript 3. All scripts on object instances will be ignored.
  1. The warning is pretty clear that you have code being ignored which is placed on an instance. The first thing to do is to find where the code is. This sample is simple enough that you could just click the objects on the Stage and view the Actions panel. In a more complex file, you could open the Movie Explorer panel to search for code placement throughout the main timeline or items in the Library. Using either method, locate the code placed on the movie clip instance and each button instance, and delete the ActionScript in the Actions panel.
  2. Add a new layer to the main timeline and name it actions.
  3. Select the keyframe on the actions layer and open the Actions panel. Click the pushpin icon on the bottom of the panel to pin the script.
  4. Click the start button and cut the code to the Clipboard. Paste the code into the Actions panel. Repeat the process for the stop button and the movie clip code.
  5. At this point you need to rewrite the code in ActionScript 3 syntax. Before you do so, make sure that each of the instances on the Stage has an instance name; start_btn, stop_btn, and circle_mc.
  6. Back in the Actions panel, update the script so that it looks like the following code:
var animate:Boolean = false; var speed:Number = 10; // Enterframe... function enterFrameHandler(event:Event) { if( animate ){ circle_mc.x += speed; if( circle_mc.x >= stage.stageWidth ){ circle_mc.x = -circle_mc.width; } } } addEventListener(Event.ENTER_FRAME, enterFrameHandler); // Button events function clickHandler(event:MouseEvent) { if( event.target == start_btn ){ animate = true; }else if( event.target == stop_btn ){ animate = false; } } start_btn.addEventListener(MouseEvent.CLICK, clickHandler); stop_btn.addEventListener(MouseEvent.CLICK, clickHandler);
  1. Run Test Movie. You should see the buttons and animation working with the code syntax and code placement updated for ActionScript 3.
 
Sample 3: Migrating text field variable and link settings
Using the variable and link fields on a text field object has been deprecated since Macromedia Flash 5, but I still find that I run into migration issues with this feature while updating older content files.
 
Follow these steps to update an ActionScript 2 file containing deprecated text fields:
 
  1. Open the designer_sample3.fla file in Flash Professional CS5.
  2. Run Test Movie to view the working ActionScript 2 file. Notice that the text in the text field updates whenever you click a button. If you were to view the SWF file in a browser, you would be able to click the field to activate the embedded link.
  3. Close the SWF file and spend a moment exploring the FLA file.
  4. Convert the file to the ActionScript 3 format by choosing File > Publish Settings. In the Publish Settings dialog box, click the Flash tab and switch the Script menu to ActionScript 3. Click OK.
  5. Run Test Movie again. Notice that warnings appear in the Output panel:
Warning: Text field variable names are not supported in ActionScript 3. The variable buttonState used for an unnamed text field will not be exported. Warning: Actions on button or MovieClip instances are not supported in ActionScript 3. All scripts on object instances will be ignored.
  1. You can see from the warnings that there are two problems occurring here. First, the text field instance is using an unsupported feature. Second, event code is placed directly on the buttons.
  2. Reformat the text field by selecting it and then modifying its properties in the Property inspector. Change the field's Text type from Dynamic to Static and then back to Dynamic. This step clears the variable and link data associated with the field. Assign the field the instance name status_txt in the <Instance Name> field.
  3. Click the Embed button next to the Character Style field and check the Basic Latin option to embed the Arial typeface. This step avoids a warning about font embedding.
  4. Select the Start button and delete the code from it using the Actions panel. Name the button instance start_btn in the Properties inspector.
  5. Select the Stop button and delete the code from it. Name the instance stop_btn.
  6. Add a new layer to the main timeline and name it actions.
  7. Select the keyframe on the actions layer and enter the following code in the Actions panel:
// Button clicks set text field function clickHandler(event:MouseEvent):void { if( event.target == start_btn ){ status_txt.text = "Start"; }else if( event.target == stop_btn ){ status_txt.text = "Stop"; } } start_btn.addEventListener(MouseEvent.CLICK, clickHandler); stop_btn.addEventListener(MouseEvent.CLICK, clickHandler); // Text clicks launch link in browser function textClickHandler(event:MouseEvent):void { navigateToURL(new URLRequest("http://www.adobe.com"),"_blank"); } status_txt.addEventListener(MouseEvent.CLICK, textClickHandler);
  1. Run Test Movie. You should see the file run without any errors and the buttons should update the text field when clicked. Clicking the text field launches the Adobe site.
 
Sample 4: Migrating linkage settings and symbol instantiation
The linkage identifier field is no longer available for symbols in an ActionScript 3 FLA file. Instead, a similar process is used with a Class and Base Class field in the symbol properties.
 
Follow these steps to update an ActionScript 2 file containing outdated linkage identifiers:
 
  1. Open the designer_sample4.fla file in Flash Professional CS5.
  2. Run Test Movie to view the working ActionScript 2 file. Notice that you can click either circle and drag it around the Stage. In this sample, the drag functionality is defined in an external ActionScript class (Circle.as) and assigned to the Circle symbol in the Library through the symbol's linkage identifier property.
  3. Close the SWF file and spend a moment exploring the FLA file.
  4. Convert the file to the ActionScript 3 format by choosing File > Publish Settings. In the Publish Settings dialog box, click the Flash tab and switch the Script menu to ActionScript 3. Click OK.
  5. Run Test Movie again. Notice that an error appears in the Output panel:
5007: An ActionScript file must have at least one externally visible definition.
  1. The first problem to resolve here is that the Circle.as class is written in ActionScript 2 syntax, so it causes an error when the ActionScript 3 compiler runs. Open Circle.as in Flash Professional and take a moment to examine the file.
  2. Create a new ActionScript file and paste the following code into it:
package { import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; public class CircleAS3 extends MovieClip { //****************** // Constructor: public function CircleAS3() { trace("INIT: "+this.name); addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); } //****************** // Events: private function addedToStageHandler(event:Event):void { addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler); stage.addEventListener(MouseEvent.MOUSE_UP, onReleaseHandler); } private function onPressHandler(event:MouseEvent):void { this.startDrag(false); } private function onReleaseHandler(event:MouseEvent):void { this.stopDrag(); } } }
  1. Take a moment to compare the code. Notice the difference in the class constructs and the event handler assignment.
  2. Save the file as CircleAS3.as in the same folder as the FLA file.
  3. Right-click the Circle symbol in the Library and choose the Properties option to launch the Symbol Properties dialog box. Click the Advanced button to show the advanced options if they are not already visible. Notice that the ActionScript 2.0 linkage Identifier field is disabled. Change the ActionScript 3.0 Class field to CircleAS3. This targets the ActionScript 3 class you just created.
  4. Run Test Movie again. Notice this time that you see a series of errors related to the code on frame 1 of the main timeline. The dynamically created instances do not have their names declared and attachMovie and getNextHighestDepth methods no longer exist in ActionScript 3. This script requires a rewrite:
Scene 1, Layer 'actions', Frame 1, Line 4 1120: Access of undefined property circle1_mc. Scene 1, Layer 'actions', Frame 1, Line 5 1120: Access of undefined property circle1_mc. Scene 1, Layer 'actions', Frame 1, Line 10 1120: Access of undefined property circle2_mc. Scene 1, Layer 'actions', Frame 1, Line 11 1120: Access of undefined property circle2_mc.
  1. Update the code on frame 1 of the main timeline to match the following script. Notice that the attachMovie command has been replaced by the new keyword. All instances, including symbol instances, are now created in this way:
// Create first clip var circle1_mc:MovieClip = new CircleAS3(); circle1_mc.x = 100; circle1_mc.y = 50; addChild(circle1_mc); // Create second clip var circle2_mc:MovieClip = new CircleAS3(); circle2_mc.x = 300; circle2_mc.y = 50; addChild(circle2_mc);
  1. Run Test Movie again. This time you can see the movie export without errors.
Tip: The ActionScript 3 language standardizes tasks. You'll use the new keyword to create new instances of all objects in ActionScript. The attachMovie and createEmptyMovieClip commands are no longer used to create movie clip instances dynamically.
 

 
Debugging tips for developers

Understanding the ActionScript 3 FLA file environment is necessary for debugging your project, but it's a fairly simple topic once you get it worked out. You'll spend most of your time debugging ActionScript-related issues if you're using any extended amount of code.
 
This section provides an overview of the types of issues you'll deal with while working with the ActionScript 3 programming language in Flash Professional.
 
 
Common issues ActionScript developers encounter
ActionScript 3 developers will commonly encounter errors and warnings during development. Overall, it's nothing to be concerned about—you can sit back and appreciate that the application is helping you to see issues as they occur during development.
 
You'll commonly deal with errors and warnings related to the following:
 
  • Compile-time errors and runtime errors
  • Frame script errors and ActionScript class errors
  • Null and undefined data errors
  • Type errors
  • CPU related issues / garbage collection issues
Note: For more information on CPU issues and garbage collection in the Flash Player, see Grant Skinner's article, Understanding garbage collection in Flash Player 9.
 
 
Best practices for avoiding errors and handling errors when they occur
You can use several techniques to prepare your ActionScript code to handle errors. By implementing proper error handling, you'll improve the performance of your application and the related user experience:
 
  1. Test your work constantly.
  2. Listen for error events wherever possible.
  3. Handle ActionScript exceptions using try catch statements.
While it may sound obvious, you will want to run the Test Movie command often as you write your ActionScript code. It's easier to identify problems if you test line by line. It becomes less necessary to test this often as you become more familiar with the ins and outs of the ActionScript 3 language.
 
Objects in ActionScript provide notifications about errors either through error events or ActionScript exceptions. Wherever you can, listen for events related to errors and status changes. Not only will you prevent unwanted crashes in the application flow, but you'll have access to timing hooks which you can use to provide a proper user experience when issues arise.
 
When error events are unavailable, you can use try catch statements to handle ActionScript errors. You might ask the question, "at what granularity do you use try catch statements?" Some developers use quite a few, while other developers don't use the feature at all. Myself, I usually place try catch statements around problem areas.
 
 
Debugging tools
ActionScript programmers tend to get creative with ways of testing and debugging their applications. In the Flash Professional CS5 workspace, you have access to the following tools:
 
  • Flash Professional CS5 workspace
  • Flash Builder 4 workspace
For a full overview of the ActionScript debugger panels and debugging workflow in Flash Professional, please see Peter Elst's article, Introducing the ActionScript 3 debugger.
 
In addition to the Flash Professional workspace, ActionScript developers are also using the Flash Builder suite of debugging tools for their ActionScript projects. Flash Builder 4 is a tool designed to enable you to build and debug Flash content in the form of Flex SDK projects, ActionScript projects, or Flash Professional projects. The new development and debugging workflows between Flash Professional CS5 and Flash Builder 4 can help speed up the process of integrating code into your Flash movies and provide expanded options for debugging. You'll take a closer look at the Flash Builder workflow in the last section of this article.
 
For an overview of the Flash Builder projects, please see About Flash Builder projects in the Flash Builder 4 online documentation.
 
 
Debugging workflow
The workflow for debugging ActionScript issues is similar to the design workflow, with the exception that you're looking for code issues more specifically than FLA-related issues.
 
To debug your ActionScript code while authoring in Flash Professional:
 
  1. Publish the FLA file.
  2. Observe errors in the Output and Compiler Errors panels.
  3. Add breakpoints to your frame scripts or ActionScript classes at suspected problem areas in your code.
  4. Run the ActionScript 3 debugger to identify issues.
  5. Fix the code and test the output.
To debug your ActionScript code while working in Flash Builder:
 
  1. Create a Flash Professional project in Flash Builder, associating Flash Builder with your FLA file and project folder.
  2. Write and edit code in Flash Builder.
  3. Use the Problems panel in Flash Builder to identify issues while coding.
  4. Launch the Flash debugger to debug runtime errors in Flash Professional, or install the debug player and use the Flash Debug perspective in Flash Builder for an expanded set of runtime debugging tools.
To debug a SWF file already deployed to a server:
 
  1. Edit the ActionScript 3 publish settings properties in Flash Professional.
  2. Enable remote debugging.
  3. Publish the SWF file to the server.
  4. Right-click the SWF file in the browser to launch the remote debugger.
  5. Observe and identify issues.
Tip:Depending on the error, you may or may not need to use the ActionScript 3 debugger. The debugger tends to be most useful when a null value or stack overflow is crashing playback.
 

 
Debugging samples for developers

The following samples demonstrate common ActionScript 3 issues. Each sample is represented by two files, wherein one shows the issue and the other shows the resolution.The steps below will guide you through each issue. Along the way, you'll experience the error, find the source of the error, and resolve the issue using ActionScript.
 
Follow these steps to get started:
 
  • Download the as3_debugging_issues_cs5.zip file from the introduction page if you haven't already done so.
  • Unzip the file to a location on your desktop. You'll be asked to open certain supplied files in the steps to follow.
  • Check out the completed files in the solutions folder for more reference.
 
Sample 1: Undefined and null values
You'll most likely run into this issue a lot. You'll trigger an error if you try to access a property or function that does not exist. The issue is usually easy to fix, but the Output panel often doesn't tell you which property is undefined. In this case, your fastest solution is to use the ActionScript 3 debugger to identify the source of the issue.
 
Follow these steps to locate and resolve an issue with an undefined value:
 
  1. Open the developer_sample1.fla file in Flash Professional CS5.
  2. Run Test Movie to view the sample. Notice that an error appears stating that a value is null or undefined. Also notice that one of the author names appears as undefined:
TypeError: Error #1010: A term is undefined and has no properties. at developer_sample1_fla::MainTimeline/frame1()[developer_sample1_fla.MainTimeline::frame1:12]
  1. Close the SWF file.
  2. Take a look at the code on the actions layer. It's fairly easy to see that there are a couple of problems in this sample, but it might not be so easy to see them at a glance if the list was larger and more complex. You can use the debugger to search for issues. Click the column to the left of line 12 to add a breakpoint to the script (see Figure 6). This step enables the debugger to pause at this point in the code execution so that you can examine the variables.
You can add breakpoints to the left of the script line numbers
Figure 6. You can add breakpoints to the left of the script line numbers
  1. Open the Variables panel and Debug Console if they are not already opened.
  2. Choose Debug > Debug Movie > Debug (In Flash Professional) to start the debugger session. Notice that the Variables panel populates with the variables active on the main timeline at the breakpoint position (see Figure 7). Expand the books list and explore the values. You can see that the list only contains three items, but the loop is set to run for four times. This is the source of the error (also noted in the debugger view with an arrow pointing to the line of code that contains the loop definition). Also, notice that the third item doesn't contain an author value. Click the End Debug Session button in the Debug Console panel to end the session.
The Variables panel is a great way to check the state of the variables in your movie; this is particularly handy when searching for null or undefined values
Figure 7. The Variables panel is a great way to check the state of the variables in your movie; this is particularly handy when searching for null or undefined values
  1. Update the script to match the following:
// Declare array variable var books:Array = new Array(); books.push({title:"ActionScript 3 Cookbook",author:"Joey Lott"}); books.push({title:"Essential ActionScript 3",author:"Colin Moock"}); books.push({title:"Adobe AIR 1.5 Cookbook",author:"David Tucker"}); // Loop through array and display text... var len:uint = 3; // it's better to use books.length here... for(var n:uint=0; n<len; n++) { books_txt.appendText(books[n].title+", by "+books[n].author+" "); }
  1. Run Test Movie again. This time the script runs without errors.
Tip: The previous sample was designed to generate an error. Normally you wouldn't hardcode a value for the len variable. Instead, you would use the array's length property so that the loop executes without generating an error.
 
 
Sample 2: Display list reference and timing errors
Objects that you instantiate in ActionScript are not automatically placed on the Stage (display list). This concept is actually very handy, as you can now run preprocessing routines on an object before it becomes visible, but as great as it is, it takes some getting used to.
 
You'll use the addChild method to add an instance to the timeline's display list. Once you do so, the instance will have access to the stage, root, and parent properties.Follow these steps to fix a file with display list instantiation issues:
 
  1. Open the developer_sample2.fla file in Flash Professional CS5.
  2. Run Test Movie to view the sample. Notice that an error related to the display list appears in the Output panel. The error doesn't define the exact location of the source of the issue, but it does hint that the problem is with the getChildIndex method. The logical way to proceed is to return to your code to search for the ActionScript statement:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. at flash.display::DisplayObjectContainer/getChildIndex() at developer_sample2_fla::MainTimeline/frame1()
  1. Close the SWF file and spend a moment exploring the script on frame 1 of the main timeline. Notice that the script creates a new Sprite instance and then tries to retrieve its index (formerly called depth) in the display list. The problem is that the instance hasn't been added to the Stage yet, so it doesn't actually exist on the display list.
  2. Update the code to match the following:
// Create a black rectangle var myClip:Sprite = new Sprite(); myClip.graphics.beginFill(0); myClip.graphics.drawRect(0,0,100,100); myClip.graphics.endFill(); // Add the instance to the Stage addChild(myClip); // Get the instance's depth in the display list... var myClipDepth:uint = getChildIndex(myClip);
  1. Run Test Movie again. This time you should see the movie export without errors, showing a black rectangle on the Stage.
Tip: To avoid display list timing problems in your ActionScript classes, you can use the ADDED_TO_STAGE event to delay display list processing until the object is added to the Stage.
 
 
Sample 3: Type errors
ActionScript 3 is a strictly typed language. To improve the performance of the compiler and the runtime playback of the movie, it's best practice to data type all your variables and functions when you declare them. Adding a data type to the declaration defines what type of data the variable or function is processing.
 
Tip: New to Flash Professional CS5 is the ability to generate import statements automatically while data-typing objects in the Actions panel.
 
Follow these steps to update a file with incorrect data type entries:
 
  1. Open the developer_sample3.fla file in Flash Professional CS5.
  2. Run Test Movie to view the sample. Notice that 3 compiler errors are generated (see Figure 8). The nice thing about compiler errors is that they tell you exactly where the source of the problem is in the code.
Compiler Errors panel showing the location and line numbers of the code generating the errors
Figure 8. Compiler Errors panel showing the location and line numbers of the code generating the errors
  1. Close the SWF file.
  2. Right-click the description of the first error in the Compiler Errors panel and choose Go to source. The Actions panel opens with the closing bracket of the addToScore function highlighted. From here, you'll read the errors and go down the lines fixing the code.
  3. Update the code to match the following script. Notice that the score and increment values were changes to the Number data type (Number instead of uint because the numbers contain decimals) and the function's return value was changed to the void data type (meaning it returns nothing). Also notice that the event object was updated to the MouseEvent data type. This wasn't causing an error because a MouseEvent is an Event, but it should explicitly match for good measure:
// Create Number variable var score:Number = 0; var increment:Number = .2; function addToScore(event:MouseEvent):void { score += increment; score_txt.text = "Score = "+score; } add_btn.addEventListener(MouseEvent.CLICK, addToScore);
  1. Run Test Movie again. This time the movie exports without error.
 
Sample 4: IO errors
IO errors occur when you try to load an external file, but the process fails. In ActionScript 3 you'll use error events or try catch statements to handle these errors gracefully and provide meaningful feedback to the user experience.
 
Follow these steps to handle an issue with loading a SWF file:
 
  1. Open the developer_sample4.fla file in Flash Professional CS5.
  2. Run Test Movie to view the sample. Notice that an error appears when the script fails to load the image. Since this is an aynchronous error, your best bet is to use the Loader's contentLoaderInfo IOError event and HTTPStatus event. This will resolve the unhandled IOErrorEvent currently being generated:
Error opening URL 'http://www.dancarrdesign.com/images/test.jpg' Error #2044: Unhandled IOErrorEvent:. text=Error #2036: Load Never Completed.
  1. Close the SWF file.
  2. Update the code on frame 1 to match the following script. Notice that the update contains event handlers for the completion of the loading, or the failed attempt:
import flash.events.*; function completeHandler(event:Event):void { // Add image to the Stage when loaded... addChild(event.target.content); } function statusHandler(event:HTTPStatusEvent):void { // Respond to status notifications... trace("HTTP Status: "+event.status); } function errorHandler(event:IOErrorEvent):void { // The image failed to load. Show feedback and proceed... trace("IOERROR: "+event.text); } // Create a Loader to load an image... var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); loader.load(new URLRequest("http://www.dancarrdesign.com/images/test.jpg"));
  1. Run Test Movie again. You see the script fail again, but this time a trace actions fires showing that you have control over the event. From here you would craft some sort of feedback that would provide the user with a clear indication of what's happened.
 
Sample 5: Security errors
Flash Player implements a security model that protects each SWF file and your computer from malicious attacks. When all your files are running within the same domain, you usually won't hit any security errors. However, it's common that you might want to aggregate content and data from different servers running on different domains. In that case, you will most likely hit security errors at one point or another.
 
Follow these steps to resolve a data loading security issue:
 
  1. Open the developer_sample5.fla file in Flash Professional CS5.
  2. Run Test Movie to view the sample. The movie is attempting to load XML data from a file located on my server. Since my domain (dancarrdesign.com) is outside of the domain from which you're viewing the SWF file, it's possible there will be a security issue here. To make the matter a bit more confusing, you most likely won't encounter the security error until you run the test file on the internet. That means that while you're testing the file in your local development environment, the file is running with a different set of security rules than it is when running from the internet. Your best option in this case is to load a permissions file from the domain serving the data.
  3. Take a look at the supplied sample. In this case, I'm loading a permissions file called crossdomain.xml that contains a global flag allowing data exchange with all domains.
  4. Close the files.
Security restrictions tend to be most strict when loading data from different domains or when cross-scripting between one SWF file loaded into another. When loading data from a different domain, using the permissions file is your best option (the supplied files include a sample of a crossdomain.xml file). When cross-scripting between SWF files, you can use the Security object's allowDomain method in ActionScript.
 
Tip: I've noticed that my application fails silently and seemingly unexplainably when I hit security issues. I usually either assume it's a security-related issue and try to allow permissions, or I log calls from ActionScript to JavaScript to expose security error events or similar information at runtime. You can use the ExternalInterface object in ActionScript or acquire a third-party resource to set up this type of logging routine.
 

 
Working with Flash Professional and Flash Builder to analyze your code

Flash Professional CS5 offers two options for using the ActionScript 3 Debugger: you can run the debugger directly from Flash Professional, or you can run the debugger by launching it from Flash Builder 4. In addition, Flash Builder has its own set of debugging tools that work with the debug version of the Flash Player to provide an expanded range of debugging options.
 
The new integration between Flash Professional CS5 and Flash Builder 4 is designed to give you an easy way to use the power of the Eclipse text editor along with the stuff you routinely do in Flash Professional. To take advantage of working with Flash Builder, you'll write your code in ActionScript classes, which can be linked to the main timeline of the FLA file or any movie clip symbol in the FLA file's Library.
 
This section will guide you through the debugger workflow options.
 
 
Reviewing the state of variables in a dynamic application in Flash Professional
This sample shows you how to use Flash Professional to explore a script that randomly generates a series of shapes whenever you click the Stage. The effect is working pretty well, but what if you wanted to analyze the random values being generated so that you can tweak the parameters? One thing you can do is to set a breakpoint in the loop that generates the shapes so that you can observe the random numbers as they occur while executing in the debugger.
 
Follow these steps to explore the variable values being generated inside an ActionScript loop:
 
  1. Open the developer_sample6.fla file and the ShapeRamdomizer.as file in Flash Professional CS5.
  2. Run Test Movie to view the sample. Notice that a random pattern of ovals is drawn to the screen. Click anywhere on the Stage to see the pattern randomly redraw itself.
  3. Close the SWF file and spend a moment exploring the ShapeRandomizer.as file. Notice that the draw function generates the shapes by running through a loop. Also notice that several variables are randomly generated to define the x, y, width, height, color, and border thickness of the shape.
  4. Click in the column just to the left of line 42 to add a breakpoint to that line. This will enable you to pause the debug player each time you run through the loop; and, while doing so, you can check out the state of the variables.
  5. Return to the developer_sample6.fla file. Open the Debug Console and Variables panels from the Window menu if they are not already open.
  6. Choose Debug > Debug Movie > Debug to launch the debugging session. Notice that the Variables panel updates to display the random values for the first pass through the loop (see Figure 9).
Variables and Debug Console panels used to step through and analyze the state of variables while a loop is occurring
Figure 9. Variables and Debug Console panels used to step through and analyze the state of variables while a loop is occurring
  1. Click the Continue button in the top left of the Debug Console panel to step forward to the next pass through the loop. Repeat the process and make observations about the range of numbers. From here you would decide whether or not the variable settings are producing the results you're after.
  2. Click the End Debug Session button to close the session.
  3. Click the breakpoint on line 42 to remove it. The dot should disappear in the Actions panel.
Tip: You can experiment with the values of the variables by updating them in the Variables panel and then stepping forward in the code execution.
 
For more information on using the Flash Professional debugger, take a look at the Debugging ActionScript 3 section of the Flash online documentation.
 
 
Launching the ActionScript 3 Debugger from Flash Builder
Flash Builder 4 and Flash Professional CS5 have opened up the possibility for new coding workflows using Flash Builder as a text editor and Flash Professional as a content editor. Flash Builder is used to write ActionScript classes in a quick way and debug code when necessary. Flash Professional is used to manage content and implement the code by assigning it to a timeline in the FLA file.
 
This sample shows you how to generate a Flash Professional project in Flash Builder using the file you worked with in the previous example. This time, you'll update the code in Flash Builder and launch the Flash Professional debugger from the Flash Builder workspace.
 
Note: This sample assumes that you have Flash Builder 4 already installed on your computer.
 
Follow these steps to set up your Flash Builder project:
 
  1. Return to the developer_sample6.fla file in Flash Professional CS5. Open the Properties panel if it's not already open so that you may view the Document properties.
  2. Click the Edit class definition button (pencil icon) next to the Class field in the Properties panel. In the Edit ActionScript 3.0 Class dialog box (see Figure 10), select Flash Builder and click OK to launch Flash Builder.
The Edit ActionScript 3.0 Class dialog box showing the option to launch Flash Builder as the code editor
Figure 10. The Edit ActionScript 3.0 Class dialog box showing the option to launch Flash Builder as the code editor
  1. When Flash Builder launches, the Create a new Flash Professional project dialog box appears, asking you to choose the target FLA file. Your FLA file is already selected, so click Finish to generate the Flash Professional project.
  2. Notice that an ActionScript file of the same name as the FLA file is automatically generated, and the ShapeRandomizer.as file is opened for editing. In Flash Builder, you can use the Package Explorer to navigate files in your project, use the Outline pane to navigate sections of your ActionScript classes, and use the Problems pane to identify issues as you work (see Figure 11).
The Flash Builder 4 workspace
Figure 11. The Flash Builder 4 workspace
  1. Update the code in the ShapeRandomizer.as file to look like the following code:
package { import flash.display.MovieClip; import flash.events.MouseEvent; public class ShapeRandomizer extends MovieClip { //******************* // Properties: private var _numShapes:uint = 25; private var _maxWidth:Number = 200; private var _maxHeight:Number = 200; //******************* // Constructor: public function ShapeRandomizer():void { draw(); // Initialize... stage.addEventListener(MouseEvent.MOUSE_DOWN, draw); } //******************* // Events: private function draw(event:MouseEvent=null):void { this.graphics.clear(); for(var n:uint=0; n<_numShapes; n++) { var w:Number = Math.random()*_maxWidth; var h:Number = Math.random()*_maxHeight; package x:Number = Math.random()*(stage.stageWidth/2); var y:Number = Math.random()*(stage.stageHeight/2); var c:Number = Math.random()*255; var b:Number = Math.random()*10; this.graphics.lineStyle(b, c); this.graphics.drawRect(x, y, w, h); this.graphics.endFill(); } } } }
  1. Test the update by launching the Test Movie command from Flash Builder. You can either click the Test Movie in Flash Professional button in the Toolbar or simply press Ctrl + Enter (Cmd + Enter on Mac) as you normally would in Flash. The view toggles back to Flash Professional, and the SWF file exports above the FLA file, as you would expect. Notice the changes to the shape rendering.
  2. Close the SWF file. Notice that you're automatically returned to Flash Builder.
Follow these steps to debug your code in Flash Professional:
 
  1. Return to the ShapeRandomizer.as file in Flash Builder if you're not already there. Start by performing the same analysis that you did in the first part of this section—only this time, launch the Flash Professional debugger from Flash Builder.
  2. To add a breakpoint to the script in Flash Builder, double-click the gray area immediately to the left of the number 42 (line 42). You should see a dot appear next to the line number, showing that a breakpoint has been added.
  3. Click the Debug Movie in Flash Professional button (flash and bug icon) in the Toolbar to launch the debugging mode in Flash Professional. The experience is the same as in the earlier example. Step through the loop to explore the randomly generated variable values.
  4. Click the End Debug Session button in the debugger to end the session. Notice that focus returns to the script in Flash Builder.
 
Analyzing code and debugging using the Flash Debug perspective in Flash Builder
So far you've experimented with Flash Builder's integration with the Flash Professional workspace. You can also use the expanded debugging tools available in the Flash Builder 4 Flash Debug perspective. A Flash Builder perspective is a collection of panels arranged to help perform a task. In the previous example, you were working in the Flash perspective in Flash Builder. If you toggle to the Flash Debug workspace (see Figure 12), a new set of debugging views appear.
 
The Flash Builder 4 Flash Debug perspective
Figure 12. The Flash Builder 4 Flash Debug perspective
The Flash Debug perspective includes the following views:
 
  • Script view: Used to set breakpoints and edit code
  • Debug view: Used to control the execution of code and step through breakpoints
  • Variables view: Used to analyze variables at a breakpoint
  • Breakpoints view: Used to manage breakpoints
  • Expressions view: Used to watch variables by defining expressions against which to test
  • Console view: Shows trace statements, runtime errors, and messages from the debugger
As you can see, Flash Builder contains the basic debugging elements of Flash Professional, including the debug console to control stepping through breakpoints and a variables view to analyze variables wherever breakpoints or runtime errors occur. Flash Builder also expands debugging possibilities by adding tools that enable you to manage breakpoints in greater detail and set up conditional breakpoints.
 
To use Flash Builder's debugging tools, the first thing you need to do is to install the debug version of the Flash Player. The debug player is a variation of the standard Flash Player that allows trace actions and debugging features to work with a SWF file in a browser. You can install the debug player by using the installers included with the Flash Professional CS5 installation or by visiting the Flash Player download site.
 
Follow these steps to install the debug player:
 
  1. Close all the applications running on your computer.
  2. Uninstall the existing Flash Player version from your computer.
  3. Restart your computer.
  4. Open the Adobe Flash CS5 folder in your applications folder on your computer. Navigate to the Players folder and then the Debug folder inside of that. Launch the installer for Windows or Mac, depending on your OS (see the Adobe Flash Player 10.1 Read Me.pdf file for more details on the installers).
  5. Browse to a Flash movie in your browser to make sure that the installation worked.
Note: You can switch between the regular Flash Player and the debug player as much as needed. If you run into problems, see either of the following TechNotes:
 
Follow these steps to launch a debugging session in the Flash Debug persecptive:
 
  1. Launching the Flash Builder debugger is easy to do. In the Flash perspective in Flash Builder, select the developer_sample6 project in the Package Explorer.
  2. Click the Debug button (bug icon) in the Toolbar. Be sure not to click the Debug in Flash Professional button, which appears as a Flash icon with a bug on it.
  3. When you click Debug, Flash Builder changes to the Flash Debug perspective and launches a browser containing the SWF file to start the session.
  4. Notice that the randomized variables appear in the Variables view similar to the way they did in the Flash Professional debugger. Click the Resume button (play icon) in the Debug view to allow the loop to advance one more time to the next breakpoint. Notice how you can analyze the variables and change the variable values in the Variables view (see Figure 13).
The Debug and Variable views seen during a debugging session
Figure 13. The Debug and Variable views seen during a debugging session
  1. Click on the Terminate button (stop icon) in the Debug view to terminate the debugging session.
  2. Finally, click the Flash perspective button in the upper right of the Toolbar to return to the standard Flash Professional project perspective. From here, you can run the Test Movie command and resume your workflow with Flash Professional.
For more information on debugging options for projects in Flash Builder, take a look at the Debugging your applications section of the Flash Builder 4 online documentation.
 

 
Where to go from here

At this point, you should have a better understanding of the common issues and debugging techniques related to application development in Flash Professional and Flash Builder. Whether you're a designer, an ActionScript programmer, or both, these workflows will help you tackle problems and work more confidently in the ActionScript 3 environment.
 
Check out these references whenever you encounter problems: