Search code examples
actionscript-3classloopsdynamicchildren

as3 accessing Children from dynamicly added moiveclip


I am adding moiveClips and putting their position accordingly. I am placing all the dynamically added clips in one new movie clip and then centering that on stage. As a test, I see I can control the alpha in the main container but I can not access the children. How can I assess each flagButton separately? There would be several in this loop example below.

var flagButton:MovieClip;
var flagArray:Array = new Array;
var flagDisplayButtons:MovieClip = new MovieClip();
function displayFlagButtons()
{




for( var i = 0; flagArray.length > i; i++)
{
    var flagButton:MovieClip = new roundButton();
    flagButton.x = (flagButton.width + 10) * i;
    flagButton.y = stage.stageHeight - flagButton.height;
    addChild(flagButton);

    flagDisplayButtons.addChild(flagButton);
}
addChild(flagDisplayButtons);

// Works
flagDisplayButtons.x = stage.stageWidth/2 - flagDisplayButtons.width/2;

// Does not see flagButton
flagDisplayButtons.flagButton.alpha = .5;
}

GETS ERROR: TypeError: Error #1010: A term is undefined and has no properties.


Solution

  • In your example code, you have created a bunch of button instances, and one by one you have added them to the display list of flagDisplayButtons. They are on that display list in the order that you placed them.

    first instance is at index 0

    second instance is at index 1

    third instance is at index 2

    and so on.

    So if you want to access the third button you added, you could do this :

    var flagButton:RoundButton = flagDisplayButtons.getChildAt(2) as RoundButton;
    

    Now that you have created variable to reference that button, you can do any of these :

    flagButton.alpha = .5;
    flagButton.x = 100;
    flagButton.y = 200;