I'm creating an asteroids game and in my main class I'm having some trouble handling the bullets that the ship fires.
All of the bullets are of the "Bullet" class and are stored in an array called "bullets" in the main class. When bullets exit the screen, removeBullet(bulletID) in the main class is called.
private function removeBullet(id:int)
{
removeChild(bullets[id]);
bullets.splice(id);
}
In my Bullet class I have an enterFrame listener that traces "stillHere". So as soon as a bullet is added to the main stage using addChild, "stillHere" starts popping up in my output panel.
My problem is that even after I call the removeBullet, "stillHere" keeps popping up in the output panel, which tells me that the object which I tried to delete is still sticking around somewhere in the memory.
What can I do to get rid of it completely?
Because you are in ActionScript you have no direct control over when objects get removed.
The real problem you have is that your event listeners are still firing. You can obviously solve this by calling
removeEventListener
when they are deleted.However a better approach is to have just one
ENTER_FRAME
listener for the whole game. It will need to individually advance all the game elements (ship, asteroids, bullets, debris etc). This method removes any chances of you accidentally forgetting to remove event listeners, and it also makes the code clearer since you can see the order that elements will update within a time step.I usually have a
destroy
function in my temporary objects which reads something like this:As long as I call this function and then remove references to the object, it's usually collected.
My code very rarely has listeners on individual objects for this reason.