Assigning dynamic variable names to objects created in a for loop in AS3.
You have to get very creative to search these questions on google because words like “for” and “loop” are so utterly common.
If you have a loop in AS3 creating multiple variables but need them to have unique names (for later modification) you need to create something like an array to store the references.
For example, anything you create in a for loop is a temporary reference. It disappears after the loop is complete, and whatever objects were created stick around in the displayObject.
In my situation I had a loop creating my navigation elements, but needed to position each ones X positions separately.
Anyways, here is one way to reference them:
private var mcArray:Array = new Array(); // DEFINE ARRAY FIRST
private function myfunction():void{
for (var i:int=0; i<2; i++) { // THE FOR LOOP
var movieClip:MovieClip = new MovieClip(); // TEMPORARY VARIABLE
addChild(movieClip);
mcArray[i] = movieClip; // here is where we add the movieClip references to the array for later use
}
}
Now, to use those references:
mcArray[0].METHOD_HERE;
or
for (var i:int=0; i<2; i++) {
mcArray[i].do_something = something;
}
To be absolutely clear, the above example creates two MovieClips according to the loop (while i < 2), and places each MovieClip in the mcArray array at index i (which we have defined as the integer counting the loop).
Now if I wanted to access something in those MovieClips I could use the mcArray to do so.
mcArray[0].graphics.beginFill(0x555555,1);
mcArray[0].graphics.drawRect(0,0,900,300);
mcArray[0].graphics.endFill();
or loop through the array and so something (like applying an animation to each and every mc in the Array
simple as that.