19 July 2009

AS3 addChild looping methods

Monster For this article, simply import a image and convert it into movie clip. In the Library, give it the class name Monster.



The Base class field will automatically be populated for you, but if it hasn't, make sure to enter flash.display. MovieClip as shown in the above image.

You would have to repeat a statement multiple times if you want to have an action executed more than once. For example, lets say, you want to create five MovieClips and add them to the display list. The long way for doing this would have been to type the command five times:


var enemy1 = new Monster(); 
enemy1.x = 0 
addChild(enemy1); 
var enemy2 = new Monster(); 
enemy2.x = 50 
addChild(enemy2); 
var enemy3 = new Monster(); 
enemy3.x = 100 
addChild(enemy3); 
var enemy4 = new Monster(); 
enemy4.x = 150 
addChild(enemy4); 
var enemy5 = new Monster(); 
enemy5.x = 200
addChild(enemy5);

However, you can do the same exact thing using a loop without having to type the same code multiple times, which is smarter way of doing it.

You can use either of the following methods.

Method 1

var enemy:Array = new Array();
for(var i:Number = 0; i < 5; i++) 
{
enemy[i] = new Monster();
addChild(enemy[i]); 
enemy[i].x = i*50;
}


Method 2

for(var i:Number = 0; i < 5; i++) 
{
var enemy:Monster = new Monster();
addChild(enemy); 
enemy.x = i*50;
}

Output







This second code generates the same exact result, but in a much more compact way. Using a loop also makes it less likely for you to have typing errors because you type the code once and then it is automatically repeated(looped).



You can always find out more at AS3 language reference Livedocs