如果项目在舞台上,则从舞台中删除多个孩子

时间:2014-04-17 14:32:36

标签: actionscript-3 flash

下午好。

我正在制作游戏,而在游戏中你知道,当你摧毁一个物体时,你必须将它从舞台上移除。

我的敌人已经通过代码动态添加,如果用户返回,敌人仍然会在显示列表中。

我试图通过尝试此代码来移除敌人。

            removeChild(character); /removes player

            removeChild(ground); // removes ground 

childrenOnStage是一个等于this.numChildren

的数字
            for (var b:int = 0; b  < childrenOnStage; b++)
            {   
                if (getChildAt(b).name == "enemy")
                {
                    removeChild(getChildAt(b));
                }

            }   

当用户从游戏返回主菜单时,它会运行此代码。

代码循环通过舞台上的所有孩子,并且应该删除那些具有敌人名字的孩子。

但是我收到了错误

[Fault] exception, information=RangeError: Error #2006: The supplied index is out of bounds.

我的问题是,我该如何移除这些敌人?

如果敌人被移除怎么办,这将导致更多的错误,例如“空对象”,即敌人不在舞台上,那么为什么我要移除这个敌人,如果它不在?

谢谢。

由于切尔诺夫回答的更新

        //after adding all of the children, this must be updated last
        childrenOnStage = this.numChildren;


    private function fromLevtoStart(e:MouseEvent):void
    {
        if (e.target == backBtn1)
        {
            stage.removeEventListener(Event.ENTER_FRAME, level1)
            stage.addEventListener(Event.ENTER_FRAME, mainGameLoop)
            //container.removeChild(_character);
            removeChild(character);
            removeChild(ground);
            for (var b:int = 0; b  < childrenOnStage; b++)
            {   
                if (getChildAt(b).name == "enemy")
                {
                    removeChild(getChildAt(b));

                    //childrenOnStage --;
                                            //update the variable below
                    childrenOnStage = this.numChildren;


                }

            }
            this.gotoAndStop("Start");
        }
    }

这仍然没有移除所有敌人,但由于某种原因只能移除一个。

它应该遍历舞台上所有名为敌人的孩子并将其删除,但事实并非如此。

在尝试下面的asnwer后,我可以说它只删除了名为“敌人”的goblin1和典型的Goblin。

        goblin1 = new Goblin();
        goblin1.name = "enemy";

        goblin2 = new Goblin();
        goblin2.name = "enemy";

当我杀死goblin1时它被移除,然后当我回到开始屏幕时,地精2甚至不是那个唯一留下了名字“敌人”的妖精,看起来只有goblin1出于某种原因被定位。

2 个答案:

答案 0 :(得分:1)

基本上,减少变量应该有效。但如果您对已删除的内容有任何疑问,可以执行以下操作:

var enemies:Array = new Array();
for (var b:int = 0; b  < childrenOnStage; b++) {
    var child:DisplayObject = getChildAt(b);
    if (child.name == "enemy") {
        enemies.push(child);
    }
}

trace(enemies);

看看你得到了什么。循环遍历enemies并删除它们 - 这样你就不需要减少任何变量,也不需要考虑numChildren - 只需删除被“标记”为敌人的所有内容。

答案 1 :(得分:1)

检查显示对象的类型,而不是检查name属性。例如:

if(getChildAt(b) is Goblin) {
    //remove
}