ActionScript (External File)

ActionScript (External File)

Flash CS4 ActionScript 3.0 Tutorial

 

How to Access ActionScript Code in a Separate .as File in Flash

 

 

There are two common ways to add ActionScript to your Flash document. The easiest method is to add your code directly to the timeline.

A second method involves writing your code in a separate .as file that is in the same directory as your .fla file. When you compile your .swf file, the external code in the .as file is included in the .swf file. This is an example of adding a rectangle to the stage as a Sprite using an external .as file.

Tutorial Elements

External .as file named GreenBox.as.

 

Step One

Open a new Flash document and save it in a folder named Project01. Name the fla file Main.fla.

Step Two

Choose File > New and select ActionScript file from the panel.

Step Three

Copy/Paste the following code to the ActionScript panel.

package {

import flash.display.Shape;

public class GreenBox extends Shape {

public function GreenBox() {

graphics.beginFill(0X4A944F);

graphics.lineStyle(2,0XAAAAAA);

graphics.drawRoundRect(50,50,100,100,6);

graphics.endFill();

}

}

}

Step Four

Click the Auto Format icon to format your code.

Step Five

Save your file in the same directory (Project01) as your .fla file. Name it GreenBox.as.

Step Six

Return to your .fla file and name the default layer Actions.

Step Seven

Option double-click (PC - Alt double-click) frame one of the Actions layer to open the Actions panel.

Step Eight

Copy/Paste the following code to the ActionScript panel.

var greenBox_mc:GreenBox=new GreenBox;

addChild(greenBox_mc);

Step Nine

Publish your movie by pressing Cmd/Return (PC - Ctrl/Enter). The green box with the rounded corners appears on the stage.

Dissecting the Code

The first line of the code at Step Three starts with the word package. The actual package of code is located in the next several lines, between the curly brackets. Since we will be extending the Shape class, we must import the Shape class in the second line. Our new class is called GreenBox. Classes generally start with capital letters and do not include any spaces.

The public class says that the Class in available to the entire project. In the function, we fill the box with green, stroke it with a two point gray stroke and set the parameters for it to be a 100 pixel by 100 pixel rounded rectangle. The rectangle's location is 50 pixels down and over from the top left corner of the stage.