AS3 I can't get removeChild to delete my items when they are listed in Array

99 views Asked by At

using ActionScript 3 on Animate, I'm trying to delete a bunch of items from the stage using Array and for loop. I actually downloaded this code from this site, but it doesn't seem to work for me. It will only delete one item and won't delete the others. and when I redraw the stage it will then not delete anything at all. I have another function button down the road that will restart (redraw) the game, I'm using the gotoAndPlay() to redraw. FYI, the "squares" are sprites and the "myTFs" are text fields that are 'paired' together to become buttons. What am I doing wrong?

function mainFunc(): void {
    var btnsArray: Array = new Array("square", "myTF3", "square2", "myTF2", "square4", "myTF4");
    for (var ii = 0; ii < btnsArray.length; ii++) {
        removeChildAt(btnsArray[ii]);
        btnsArray.length = 0;
    }
}
1

There are 1 answers

0
Organis On

If you have an Array of DisplayObject's names you want to batch operate (e.g. remove from display list or something else) you can do the following:

var A:Array = ["square", "myTF3", "square2", "myTF2", "square4", "myTF4"];

// Iterate over items of the Array.
for each (var aName:String in A)
{
    // Obtain a reference to the object by its instance name.
    var aChild:DisplayObject = getChildByName(aName);
    
    // Check if it is a valid instance before removing to avoid errors.
    if (aChild)
    {
        removeChild(aChild);
    }
}