0

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;
    }
}
  • [`removeChildAt()`](https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#removeChildAt()) takes an integer index. You're giving it a string. Use [`getChildByName()`](https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#getChildByName()) and [`removeChild()`](https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#removeChildAt()) – Pranav Hosangadi Oct 20 '20 at 21:07
  • Also, you set the **Array**'s length to zero on the first iteration, there's nothing in that **Array** after the first go. – Organis Oct 20 '20 at 23:12

1 Answers1

1

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);
    }
}
Organis
  • 7,243
  • 2
  • 12
  • 14