I’ve built a simple snake game that uses a Main class (this is my document class), a Snake class and a Food class. The Main class makes a new object of the Snake class, and another of the Food class. Within both the Snake and Food classes, I’m making sprites like so:
var segment:Sprite = new Sprite();
segment.graphics.beginFill(0xFFFFFF);
segment.graphics.drawRect(0, 0, 10, 10);
segment.filters = [new GlowFilter(0xFF6699, .50, 3, 3, 2, 2, false, false)];
segment.graphics.endFill();
segment.x = x;
segment.y = y;
this.stage.addChild(segment);
this.segments.push(segment);
The snake’s body is stored in an array of sprites called segments. You can see from that code I’m making a new sprite to extend the length of the snake and pushing it to the segments array. I do something similar for any food items, except within the food class I’ve defined the food sprite as public var foodSprite:Sprite; because I only need one on the stage at a time.
Now, when I call the gameOver() method from the Main class (where I have my game loop), I want to call stage.removeChild() on each of the snake segments and the food sprite. I tried doing this:
for(var i:Number = 0; i < this.snake.segments.length; i++)
{
stage.removeChild(this.snake.segments[i]);
}
But I get this error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/gameOver()
From what I know this should work, as this.snake.segments[i] points to a sprite, the one which I want to remove from the stage.
What could be going wrong here? Thank you.
EDIT: I guess it’s also worth noting that segments is defined as:
public var segments:Array = new Array;
Try this: