0

So, my question is as follows.

Why am I getting this error

(TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/removeChild() at TargetMain/killTarget())

when trying to remove objects from the stage with a mouse click?

My code for the application is below.

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

Any help is greatly appreciated.

2 Answers2

0

The error means deadTarget is null, so if you just want to remove deadTarget from stage, try this

 var deadTarget:DisplayObject = toDie.target as DisplayObject;

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

Or you should find out the actural type of deadTarget.

Pan
  • 2,101
  • 3
  • 13
  • 17
0

You are listening for click on stage. So, any clicks (whether it's on ParaspriteFull object or not) would fire killTarget. One way to avoid exception is to do as Pan has suggested in the answer to essentially do nothing in click killTarget if the clicked object isn't of type ParaspriteFull. But, I'd suggest to listen for clicks on ParaspriteFull objects and not on stage. i.e. remove

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

from your constructor and modify spawner function to add click listener as:

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

Also, remove listener on ParaspriteFull object in killTarget as:

deadTarget.removeEventListener(MouseEvent.CLICK, killTarget);//Remove clicking function listener
catholicon
  • 1,165
  • 2
  • 8
  • 15