1
votes

I'm making a game where if the enemy's bullet hits the user, the bullet disappears. Everything works fine except that I keep getting,

'Error #1009: Cannot access a property or method of a null object reference'

Once the bullet hits the user (bullet disappears though). It confuses me because I've used almost exact the same code in another class where it works perfect.

package classes.enemy 
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import classes.Main;

public class Bullet extends MovieClip
{
    var speed:Number;

    public function initialize()
    {
        var stageReff:Stage = this.stage as Stage;
        stage.addEventListener("enterFrame", enterFrame);
    }

    //code 

    function enterFrame(e:Event):void
    {
        this.x += speed;

        if(this.hitTestObject(Main.user))
        {
            removeEventListener("enterFrame", enterFrame);
            this.parent.removeChild(this);
            // line above gives the error.
        }
    }
}
}

I have no clue what could be wrong. Thanks in advance.

3
run in debug mode, find the line that is throwing the error. It might be at this.parent.removeChild(this) but I could be wrong. If it is it might be that this is no longer a child of the parent. - ToddBFisher
It is the line: this.parent.removeChild(this);. If I comment it out it works without errors (but then the bullet doesn't disappear ofc). - Robbe Van Winckel

3 Answers

2
votes

My guess is it has to do with the fact that you're adding an enter frame event listener to the stage, yet try to remove it from the listening object itself.

Try changing

var stageReff:Stage = this.stage as Stage;
stage.addEventListener("enterFrame", enterFrame);

to

addEventListener("enterFrame", enterFrame);
0
votes

you're not removing the event listener from the stage, but the object itself :)

I would not recommend doing it like this, create one listener in your main game class, and call an update function on all objects!

0
votes

The reason why it fails is because you're removing your Bullet from it's parent. So when you're referencing this.parent it returns null because there simply isn't a parent anymore. You're trying to remove the ENTER_FRAME event but because you set it on the stage the original ENTER_FRAME event keeps running. You can simply fix it like so:

if(this.x > 30)
{
    stage.removeEventListener("enterFrame", enterFrame);
    this.parent.removeChild(this);
}

But like @RasmusWriedtLarsen already pointed out, it's better to handle these events more globally. And also let the parent handle the removing of the Bullet.