ActionScript: Removing all Children From the Stage

I ran into an interesting problem today when I attempted to remove all objects from the Stage. I didn’t realize that there was not an ActionScript method like removeAll (or something). After about a half hour of trying I was finally able to create a script that will remove all children from the Stage.

At first, I tried this function:

?View Code ACTIONSCRIPT
private function removeAllChildren():Boolean {
        for (var i:int = 0; i < this.numChildren; i++ {
                this.removeChildAt(i);
        }
        return true;
}

This seemed logical, but it did not work. In fact, the ActionScript code was removing every other object from the Stage. After trying different variations of this, I finally realized what was wrong.

When I call:

?View Code ACTIONSCRIPT
removeChildAt(0);

After the child is removed, the next object in the creation order becomes the child at 0.

So I changed my code to:

?View Code ACTIONSCRIPT
while (numChildren > 0) {
        removeChildAt(0);
}

Worked perfectly. All children were removed. And it makes sense. I guess.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks