PDA

View Full Version : load items to stage via an array


Toyfruit
07-08-2008, 11:36 AM
Hi all, I'm just trying to learn AS3 and am having some trouble ...

I have 4 library items (all movie clips), named as mc0, mc1, mc2, mc3. The linkage is set so the class name is the same.

I want to create an array with the class names in, so I have:
var mcNames:Array = new Array(mc0, mc1, mc2, mc3);

I then want to be able to loop through (either using a for or if statement) and dynamically attach the items to the stage by looping through the array. So my code would be like:

for (var i:Number = 0; i<mcNames.length; i++){
// put an instance of the movieclip on the stage that
//has the same name as the current item in the array.
//So for example, if the first item in the array is mc0,
//then the item attached to the stage will be the
//movieclip mc0 from the library --- but how do I do it????

}

Any help would be greatly appreciated

Toyfruit
07-08-2008, 11:54 AM
OK - I think I may have found an answer myself, please correct me if this is wrong, but it seems to be working - I thought others with a similar problem might find this useful:

var mcNames:Array = new Array(mc0, mc1, mc2, mc3);
var mcCur:Number = 0;
function displayMcs():void{
if (mcCur<mcNames.length){
var mcValue:Object = mcNames[mcCur];
var myMC:MovieClip = new mcValue();
this.addChild(myMC);
mcCur++;
displayMcs();
}
}
displayMcs();

tukinu
07-08-2008, 11:59 AM
you could do it like this:

for(var i:Number = 0; i<mcNames.length; i++){


var _cont:Sprite = new Sprite();

var mc = getDefinitionByName("mc" + i);

_cont = new mc();
addChild(_cont);

_cont.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);

}

private function onAddedToStage(e:Event):void{

// info about the mcs now available

}

the ADDED_TO_STAGE is needed to have all information of the movieclips. you won't have them until is really added to the stage.