Wednesday, 1 February 2012

DisplayObjectContainer removeChildren in FP11

In Flash Player 11 there is new method called removeChildren() that removes all the children from a container object. The removeChildren() method simply removes all the children and makes them available for garbage collections.

This example is the technique for removing all the children from a container object prior to Flash Player 11. You use the While loop to check if any children objects exist on the stage then use the removeChildAt() to remove all the children.

for(var i:uint = 0; i < 50; i++){
 var rec:Shape = new Shape();
 rec.graphics.beginFill(0x000000);
 rec.graphics.drawRect(0,0,50,50);
 rec.graphics.endFill();
 rec.x = Math.random() * stage.stageWidth;
 rec.y = Math.random() * stage.stageHeight;
 addChild(rec);
}

stage.addEventListener(MouseEvent.CLICK, clicked);

function clicked(e:MouseEvent):void{
 while(numChildren > 0) removeChildAt(0);
} 

This works the same if you add the child objects inside a container movie clip like below.

var container:Sprite = new Sprite();
addChild(container);

for(var i:uint = 0; i < 50; i++){
 var rec:Shape = new Shape();
 rec.graphics.beginFill(0x000000);
 rec.graphics.drawRect(0,0,50,50);
 rec.graphics.endFill();
 rec.x = Math.random() * stage.stageWidth;
 rec.y = Math.random() * stage.stageHeight;
 container.addChild(rec);
}

stage.addEventListener(MouseEvent.CLICK, clicked);

function clicked(e:MouseEvent):void{
 while(container.numChildren > 0) container.removeChildAt(0);
}

In Flash Player 11 the code will look like this. The removeChildren() method has two optional parameters, look at the AS3 documentation for more information.

for(var i:uint = 0; i < 50; i++){
 var rec:Shape = new Shape();
 rec.graphics.beginFill(0x000000);
 rec.graphics.drawRect(0,0,50,50);
 rec.graphics.endFill();
 rec.x = Math.random() * stage.stageWidth;
 rec.y = Math.random() * stage.stageHeight;
 addChild(rec);
}

stage.addEventListener(MouseEvent.CLICK, clicked);

function clicked(e:MouseEvent):void{
 stage.removeChildren();
}

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP