I have used this code in my AS3 document class to remove all objects from the stage:
var _stage:DisplayObjectContainer = stage as DisplayObjectContainer;
while (_stage.numChildren > 0) {
_stage.removeChildAt(0);
}
and this appears to be working very well with one exception. After I run this, a button can be pressed to re-load everything onto the stage. In this construction function, some conditionals are added to create event listeners for the stage if they don't already exist:
if(!stage.hasEventListener(KeyboardEvent.KEY_DOWN));
stage.addEventListener(KeyboardEvent.KEY_DOWN, handle_key);
if(!stage.hasEventListener(MouseEvent.MOUSE_MOVE));
stage.addEventListener(MouseEvent.MOUSE_MOVE, manage_cursor);
EDIT: stage definitely is null, I put if(stage){}
around this section of code, and the error cropped up at the next point in the code that stage is used
I receive an error however, on the reconstruct, TypeError: Error #1009: Cannot access a property or method of a null object reference.
in reference to "stage".
Further research indicates that it might be possible that removing all DisplayObjects from the stage removes the ability to access the stage itself until a DisplayObject is added in. however, this doesn't make any sense to me whatsoever and I am not entirely sure how to proceed.
Any help would be greatly appreciated.
If you are calling "stage" from within a MovieClip, the reference will ONLY be non-null when the MovieClip is on the display list. The Stage always exists once Flash is loaded, but individual MovieClip instances can gain/lose reference to it when they are added/removed from the display list.
This even applies to your document root instance. As soon as any DisplayObject is removed from the display list, its' stage reference is set to null.
Here's an example using the root document that illustrates the concept:
This code will output:
Note the loss of the stage reference after removing the object from the display list.
In your example, you are looping over every child of the stage, and removing each of them. That will definitely cause your stage reference to be lost because of the same concept as shown above.