尝试通过鼠标单击删除孩子

时间:2013-07-23 16:09:16

标签: actionscript-3 removechild addchild displayobject

所以,我的问题如下。

为什么我收到此错误

(TypeError:错误#2007:参数child必须为非null。     在flash.display :: DisplayObjectContainer / removeChild()     在Tar​​getMain / killTarget())

尝试用鼠标单击从舞台中删除对象时?

我的应用程序代码如下。

package
{
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.ui.Keyboard;

    public class TargetMain extends MovieClip
    {
        public function TargetMain()
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, spawner);//Spawning function listener

            stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener
        }

        public function spawner(k:KeyboardEvent):void
        {
            if(k.keyCode == 32)
            {
                trace ("spawned");
                var theTarget:ParaspriteFull = new ParaspriteFull();

                theTarget.x = Math.floor(Math.random() * stage.stageWidth);
                theTarget.y = Math.floor(Math.random() * stage.stageHeight);
                addChild(theTarget);

            }
        }

        public function killTarget(toDie:MouseEvent):void
        {
            trace ("clicked")
            var deadTarget:ParaspriteFull = (toDie.target as ParaspriteFull);
            //Below is where I continually get an error and do not know how to fix it.
            //This is also after searching the internet for hours trying to solve my issue.

            //MovieClip(deadTarget).parent.removeChild(deadTarget);
            removeChild(deadTarget);
        }
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

错误意味着deadTarget为null,所以如果你只是想从stage中删除deadTarget,试试这个

 var deadTarget:DisplayObject = toDie.target as DisplayObject;

 if ( deadTarget && deadTarget.parent) {
     deadTarget.parent.removeChild(deadTarget);
 }

或者你应该找出deadTarget的实际类型。

答案 1 :(得分:0)

您正在聆听点击舞台。因此,任何点击(无论是否在ParaspriteFull对象上)都会触发killTarget。避免异常的一种方法是,如果被点击的对象不是ParaspriteFull类型,Pan在答案中建议点击killTarget基本上什么都不做。 但是,我建议听一下ParaspriteFull对象的点击,而不是在舞台上。即删除

stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener

来自constructor并修改spawner功能,将点击监听器添加为:

theTarget.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener

另外,删除killTarget中ParaspriteFull对象上的侦听器:

deadTarget.removeEventListener(MouseEvent.CLICK, killTarget);//Remove clicking function listener