1

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.

4

4 回答 4

3

实际上 5 次迭代的循环完成得非常快,以至于按下按钮时您无法退出循环。

我的理解是您想在按下按钮时删除添加的 5 个太阳。

我的建议是创建您的 5 个太阳的父级并将其添加到该父级并删除您的父级,以便删除所有 5 个子级。无需维护 5 个子引用,您只需维护一个父引用。

于 2012-06-13T12:14:10.333 回答
0

将“太阳”存储在一个数组中并循环遍历以删除所有太阳:

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]);
    } 
}

或者你删除所有:

function RemoveAll() {
    for(var i:int = 0; i < this.numChildren; i++) {
        this.removeChildAt(i);
    }
}
于 2012-06-13T13:00:12.433 回答
0

这是您需要的(底部的函数)以及对原始发布代码的小改动。

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);
    }
}
于 2012-06-15T18:36:20.910 回答
0

停止循环并使用 break 命令退出;因此,如果您有一个可以像 var menuClicked 一样检查的条件,您可以这样做:

for (counter = 0; counter < aantalSun; counter++)
{
 if(menuClicked) break;
 sun = new Sun();
 addChild(sun);
}
于 2012-06-13T12:12:53.580 回答