Question

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.

Was it helpful?

Solution

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:

package
{
    import flash.display.Sprite;
    import flash.events.Event;

    [SWF(width="800", height="600", frameRate="60"]
    public class Main extends Sprite
    {
        public function Main()
        {
            addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true);
        }

        private function onEnterFrame(event:Event):void
        {
            if (stage != null)
            {
                trace("stage: "+stage);
                stage.removeChild(this);
                trace("stage: "+stage);

               removeEventListener(Event.ENTER_FRAME, onEnterFrame);
            }
        }
    }
}

This code will output:

stage: [object Stage]
stage: null

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top