Reputation: 11
this is a part of my code:
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
for (counter = 0; counter < aantalSun; counter++)
{
sun = new Sun();
addChild(sun);
}
when the whole code is running, there is a button called 'menu' on the stage. when i click that button, i want to go back to my main menu, but there are still 5 sun on my stage. how can i remove the 5 sun (like, stop the loop?) when i click the menu button? i already tried removeChild(sun);, but then only one sun goes away.
Upvotes: 1
Views: 219
Reputation: 14406
Here's what you need (rhe function at the bottom) as well as the small changes to your original posted code.
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
private var sunContainer:Sprite = new Sprite();
addChild(sunContainer);
for (counter = 0; counter < aantalSun; counter++)
{
sun = new Sun();
sunContainer.addChild(sun);
}
//function for clearing all suns
function clearSuns(e:Event = null):void {
var i:int = sunContainer.numChildren;
while(i--){
sunContainer.removeChildAt(i);
}
}
Upvotes: 0
Reputation: 3226
Store the "suns" in an array and loop trough this to remove all suns:
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
private var sunArray:Array = new Array();
for (counter = 0; counter < aantalSun; counter++) {
sun = new Sun();
sunArray.push(sun);
addChild(sun);
}
function RemoveSuns() {
for (var i:int = 0; i < sunArray.length; i++) {
removeChild(sunArray[i]);
}
}
OR you remove ALL:
function RemoveAll() {
for(var i:int = 0; i < this.numChildren; i++) {
this.removeChildAt(i);
}
}
Upvotes: 0
Reputation: 1573
Actually looping of 5 iterations will done so fast that you cant exit from the loop when a button is pressed.
What I understood is you want to remove the added 5 suns when the button is pressed.
What I would suggest is create parent of your 5 suns and add it to that and remove your parent so that all 5 childs will be removed. No need to maintain 5 childs references and you have to maintain only one parent reference.
Upvotes: 3
Reputation: 2779
Stop the loop and exit it with the break command; So if you have a condition that you can check like the var menuClicked you can make liek this:
for (counter = 0; counter < aantalSun; counter++)
{
if(menuClicked) break;
sun = new Sun();
addChild(sun);
}
Upvotes: 0