The error is happening because you're removing the eventListener
within the eventListener
's function and your removing the object from it's parent and still processing data that the object no longer contains or has been nullified. You should add a boolean
to tell if the hitTest
has occured and then not process any more of the loop. For instance:
private function loop(event:Event):void
{
var objectHit:Boolean = false;
objectHit = this.hitTestObject(_root.killGun);
if(!objectHit) {
if (reachedGoal == true)
{
if (goNowhere == true)
{
gotoAndStop(1);
}
//Boundaries
if (this.x <= 20)
{
goRight = true;
goNowhere = false;
}
if (this.x >= stage.stageWidth - 20)
{
goRight = false;
goNowhere = false;
}
if (this.y >= stage.stageHeight - 20)
{
yDir = 0
}
if (this.y <= 20)
{
yDir = 1
}
}
//Intro walk
if (reachedGoal == false)
{
if (this.x < actualRange)
{
gotoAndStop(4);
this.x += 3
}
if (this.x >= actualRange)
{
reachedGoal = true;
gotoAndStop(1);
}
}
}
if (objetHit)
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
}
}
You should also remove the Event.ADDED
listener once the object has been added.
private function beginClass(event:Event):void{
//defining _root as the document root
_root = MovieClip(root);
this.removeEventListener(Event.ADDED, beginClass);
}