Removing objects from the scene

There are limited resources on a device. As much as we wish they were as powerful as a desktop to hold so much memory, it's not at that point yet. This is why it is important to remove display objects from the display hierarchy when you no longer use them in your application. This helps overall system performance by reducing memory consumption and eliminates unnecessary drawing.

When a display object is created, it is added by default to the root object of the display hierarchy. This object is a special kind of group object known as the stage object.

In order to keep an object from rendering on screen, it needs to be removed from the scene. The object needs to be removed explicitly from its parent. This removes the object from the display hierarchy. This can be done in either in the following way:

myImage.parent:remove( myImage ) -- remove myImage from hierarchy

Alternatively, this can be done using the following line of code:

myImage:removeSelf( ) -- same as above

This does not free all the memory from the display object. To make sure that the display object is removed properly, we need to eliminate all the variable references to it.

Even though a display object has been removed from the hierarchy, there are situations in which the object continues to exist. To do this, we will set the property to nil: