actionscript-3runtime-errormovieclipaddchildprojectile

As3: _root.removeChild(this) not working with array IN SPECIFIC CASES?


I have a class for a ninja star.

In the loop function, I have:

    private function loop (event:Event):void
    {           
    trace(this);

        for (var i:int=0; i<_root.guardArray.length; i++) 
        {
            //if movieClip at position [i] (enemy) hits this
            if (_root.guardArray[i].hitTestObject(this)) 
            {
                if(this.hitTestObject(_root.guardArray[i].hitbox))
                {
                    _root.guardArray[i].killThis();
                    _root.removeChild(this);
                    removeEventListener(Event.ENTER_FRAME, loop);
                }
            }
        }

            y-=Math.cos(rotation/-180*Math.PI)*(ninjaStarSpeed);
            x-=Math.sin(rotation/-180*Math.PI)*(ninjaStarSpeed);


        if(this.x < 0 || this.x > _root.stagewidth || this.y > _root.stageheight || this.y < 0)
        {
            _root.removeChild(this);
            removeEventListener(Event.ENTER_FRAME, loop);
        }
    }
}

The ninja star removes itself successfully without any errors when it goes out of the screen.

HOWEVER, when it hits a guard, it removes itself but gives me a #2025 error @ line 40!

This is line 40: _root.removeChild(this); - it's part of the array collision checking.

Is flash bugged out or am I doing something VERY wrong?


Solution

  • Yep, you are doing something wrong, because of Error ;)

    Code snippet for you:

    private function safeRemove():void{
        if(this.parent != null){
            this.parent.removeChild(this);
        }
    }
    

    Add this method to the NinjaStar class, and use it. So 40-th line of code will look like

    //And don't forget not only kill guard, but also clear reference on him from the guardArray.
    _root.guardArray[i].killThis();
    safeRemove();
    removeEventListener(Event.ENTER_FRAME, loop);