I've tried for many hours, with coding and searching for solution to my problem with no effect.
Error: TypeError: Error #1009: Cannot access a property or method of a null object reference.
Briefing: I'm creating a game, been working on a background cloud spawner on random intervals and such, one of the ideas is, to make cloud fade away after her life span reaches 0 (we countdown from 100 to 0). Project is in 30 FPS. Interesting thing is, that the cloud that causes an error, disappears (maybe its still there but with 0 alpha?) but the next clouds, dont give any errors, everything works just fine.
So now it's time for some code and explanation:
GAME CLASS - document class
// VARIABLES
var clouds:Clouds = new Clouds();
static var cloudsTimerDelay:Number = 3000;
static var cloudsTimer:Timer = new Timer(cloudsTimerDelay);
// CONSTRUCTOR
cloudsTimer.addEventListener("timer", spawnCloud);
cloudsTimer.start();
// CALLED FUNCTION
function spawnCloud(e:Event){
stage.addChildAt(new Clouds,1);
}
CLOUD CLASS
// VARIABLES
var fadeSpeed:Number = 0.05;
var lifeSpan:Number = 100;
// CONSTRUCTOR
addEventListener("enterFrame", enterFrame);
// CALLED FUNCTIONS
function enterFrame(e:Event)
{
this.lifeSpan--;
this.x += this.velocity;
if (this.lifeSpan < 0)
{
this.alpha -= this.fadeSpeed;
if (this.alpha <= 0)
{
kill(); // ERROR IN THIS FUNCTION
}
}
}
function kill()
{
removeEventListener("enterFrame", enterFrame);
stage.removeChild(this); // ERROR ERROR ERROR
}
I marked the error place just above, it's the stage.removeChild(this) that's causing the problem (that's what debugger says). The main idea by this code is to create objects on stage white the set interval (the timer section), when it's created, the object start's it's own enterFrame function. It's used to move clouds, and subtract 1 from the lifespan each frame, when it reaches 0, the fading starts with changing alpha value by constant value, when alpha is lower than 0, the kill function should go in, getting rid of eventlistener and deleting the cloud from stage. Any ideas why this error occurs? I would be very grateful for any solutions! Also I'm terribly sorry if I wrote something in a bad manner but this is my first post on Stack : )
Cheers!
Okay so as i said in the comment the problem is in the Game class with
var clouds:Clouds = new Clouds();
This var is never in fact added to the stage, but it still has every other property. So when its alpha reaches 0, it will call its kill()
function, which will ask for the DisplayObject.stage
property, which is null (since it was never added to the stage). The property you cannot access mentioned in the error is removeChild
.
Remember that when you refer to stage
in a DisplayObject
class it will mean its own stage
property. The class has no way of knowing of the stage you are using, unless you add your DisplayObject
to the stage. This means that this.stage
can sometimes be null
.