So, I’m trying to remove an object after it has exceeded set x and y coordinates but i keep getting this error:
Error #1009: Cannot access a property or method of a null object reference.
I used the same code for another object and it worked fine. The error is coming from line 45 of my ship code which is: parent.removeChild(this);
and line 72 of my Level code which is: ships[count].update();
Here is my Level code :
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Mouse;
public class Level extends MovieClip
{
var ships:Array;
var bullets:Array;
public var avatar:Avatar;
public function Level()
{
avatar = new Avatar();
addChild( avatar );
avatar.x = mouseX;
avatar.y = mouseY;
//addEventListener(Event.ENTER_FRAME, loop);
ships = new Array ;
bullets = new Array ;
addEventListener(Event.ENTER_FRAME, update);
}
function update(e:Event)
{
avatar.x = mouseX;
avatar.y = mouseY;
Mouse.hide();
if (numChildren<5)
{
var s = new Ship();
addChild(s);
s.x = Math.random() * stage.stageWidth;
s.y = -30;
//s.rotation = Math.random() * 360;
ships.push(s);
}
for (var bcount=0; bcount<bullets.length; bcount++)
{
bullets[bcount].update();
if (bullets[bcount].parent == null)
{
bullets.splice(bcount, 1);
bcount--;
}
}
for (var count = 0; count<ships.length; count++)
{
ships[count].update();
for (bcount=0; bcount<bullets.length; bcount++)
{
if (ships[count].hitTestObject(bullets[bcount]))
{
trace ("HIT");
removeChild(ships[count]);
ships.splice(count, 1);
removeChild(bullets[bcount]);
bullets.splice(bcount,1);
}
}
}
}
}
}
Here is my ship code:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.display.Stage;
public class Ship extends Sprite
{
private var speed:int;
var rotateSpeed:Number;
var size:Number;
public function Ship()
{
speed = 2+Math.random()*5;
rotateSpeed = 15;
size = 5
this.scaleX = Math.random()* size;
this.scaleY = this.scaleX;
trace("Made a Ship")
}
function update()
{
this.rotation += rotateSpeed;
y = y + speed;
if (x<0 || x >500 || y < 0 || y > 500)
{
parent.removeChild(this);
}
}
}
}
Thanks in advance