PDA

View Full Version : Confused about removeChild and delete



cerupcat
October 24th, 2007, 03:23 AM
I'm trying to delete a sprite as much as it is possible.

I understand that removeChild just removes the object from the displaylist. I'm not positive though what is considered a "reference" to an object or how I would delete/null it.

Right now I am using the following code when a certain event occurs.


var index = getChildIndex(ball);

removeChild(ball);

balls[index] = null;
balls.splice( index, 1 );

while(ball.numChildren > 0){
ball.removeChildAt(0);
}

ball.removeEventListener(Event.ENTER_FRAME, checkCollision);

This works but there are some problems.

The ball is a class of it's own and has it's own eventListerners. When I run the application, I'm getting runtime errors. "Cannot access a property or method of a null object reference." So how do either avoid the error or removeEventListners from a child or other class?

Basically I have balls (sprites) that are bouncing around and hitting each other. When dragged outside a certain boundary, I want the sprite to be removed. In order for this to work completely, I need all the eventListeners to also be removed so the ball stops functioning once removed from the displaylist. The problem is that the eventListeners are in different classes and I don't know how to remove them all.

Charleh
October 24th, 2007, 04:24 AM
You remove the event listener before you remove the ball...the ball object needs to be present for it to handle your call to it's removeEventListener method. Also the same for everything else.

Remember that any variables set to reference the ball need to be unset - the ball is only actually deleted from memory when garbage collection kicks in, but this can only happen when nothing is referencing the ball.

If you remove the ball from the display list it becomes a 'null' in the display list even though there may be other objects referencing it - so it's best to remove these first using the methods of ball, and then finally remove the ball



var index = getChildIndex(ball);

// Remove references in array
balls[index] = null;
balls.splice( index, 1 );

// Remove children
while(ball.numChildren > 0){
ball.removeChildAt(0);
}

// remove listener
ball.removeEventListener(Event.ENTER_FRAME, checkCollision);

// Kill the ball
removeChild(ball);