For Statement

For Statement

Flash CS4 ActionScript 3.0 Tutorial

 

How to Assign and Check Data with Flash ActionScript

 

 

Loops are handy pieces of code if you want to fill an array, add several Loaders or check several pieces of data. In other words, loops work great to populate an array, movie clip or the stage. Once a loop starts, it consumes the processor resources. It is important that you don't create an endless loop that you can't escape.

Loops come in multiple varieties. Common loops include For, Do While and While statements.

In this example we will demo a For statement that loads several shapes to the stage. For more information on other types of loops, see topics, Do While Statement and While Statement.

 

Step One

Open a new Flash document and name the default layer Actions.

Step Two

Open the ActionScript panel for the only keyframe in the Actions layer by Option double-clicking (PC - Alt double-clicking) the keyframe.

Step Three

Copy/Paste the following code in the ActionScript Panel:

for (var i:int = 1; i<6; i++) {

var cube01:Shape=new Shape;

cube01.graphics.beginFill(0xCCCCCC);

cube01.graphics.lineStyle(2,0xAAAAAA);

cube01.graphics.drawRoundRect(10,15,50,50,4);

cube01.graphics.endFill();

addChild(cube01);

cube01.x= i*80;

}

Step Four

Click the Auto Format button to format the code

Step Five

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Five rounded rectangles appear on the stage.

Dissecting the Code

The first line of the code at Step Three defines the for statement parameters. A new integer variable is established with a value of 1. The statement will be allowed to cycle five times and each time it cycles, i is increased by one. Inside the for statement, a new Shape variable is introduced named cube01. Lines three through six define the rounded rectangle shape.

The addChild() statement adds the object to the stage and the final line distributes the multiple objects across the stage.

 

Shutterfly 50 Free Prints 160x600