Incognito
Incognito

Reputation: 351

In Actionscript 3, how do I create movieclips through a looping statement?

The statement for takes a triple as an argument

(initial value of i, condition to cease looping, i increment)

I want to create a different movie clip each time the loop goes on.

So, I tried:

for (i = 0; i < 9; i++){
    var Unit+i:MovieClip = new MovieClip()
}

But, this triggers the following error:

1086: Syntax error: expecting semicolon before plus"

What's the correct syntax, then?

Upvotes: 1

Views: 228

Answers (2)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

To address the issue. You cannot create a var dynamically by using the var keyword. So doing var Unit+i will give you a syntax error.

You can create an array ahead of time and put your objects in that (as per @Panzercrisis's answer which is perfectly acceptable).

Other ways you can do this:

If you current context is dynamic (like if this is timeline code or part of a dynamic class like MovieClip), you do something like this:

this["Unit"+i] = new MovieClip();

From a compile time checking and code maintenance perspective, this is a little sloppy in my opinion, but for quick timeline projects it's certainly acceptable.

You could also just not store the clip anywhere but the display list:

for(var i:int=0;i<9;i++){
    var mc:MovieClip = new MovieClip();
    //do whatever you need to do to the clip
    //like draw something for instance
    mc.graphics.beginFill(0xFF0000);
    mc.graphics.drawRect(0,0,100,100);

    addChild(mc); //add to the display list so you can see it
}

If you never need to remove this clip, this way is great.


Or, you could add them to a container display object

var clipContainer:Sprite = new Sprite(); //Sprite is the same as movie clip but without the timeline stuff
addChild(clipContainer);

for(var i:int=0;i<9;i++){
    var mc:MovieClip = new MovieClip();
    //do whatever you need to do to the clip
    //like draw something for instance
    mc.graphics.beginFill(0xFF0000);
    mc.graphics.drawRect(0,0,100,100);

    clipContainer.addChild(mc);
}

The clipContainer would then act the same as an array, where you can access all it's children. Also, moving/scalling the container would in turn move/scale all it's children

Upvotes: 1

Panzercrisis
Panzercrisis

Reputation: 4750

Basically this is what you want to do:

var arrMovieClips:Array = new Array(9);
for (var i:int = 0; i < arrMovieClips.length; i++)
{
    arrMovieClips[i] = new MovieClip();
}

This will create an array with nine elements, so you essentially have nine variables in a row:

arrMovieClips[0]
arrMovieClips[1]
arrMovieClips[2]
...
arrMovieClips[8]

Then it will go through and loop 0, 1, 2, etc. When it gets to the length of arrMovieClips, which is 9, then it'll stop. As it goes through 0-8, it'll create a new MovieClip and store it in each spot.

Upvotes: 1

Related Questions