What's happened to stage? Unravelling the display list

Posted: 19/01/08

An image of What's happened to stage? Unravelling the display list

You're trying to do something like:

public class MyClass extends Sprite

{

public function MyClass()

{

mySprite.x = stage.stageWidth;

}

}

but all you get is

Error #1009: Cannot access a property or method of a null object reference.

...and you have no idea why!?!?! You're using the stage property of a DisplayObject as the books and the docs tell you, but you still seem to be getting told that it doesn't exist. Well this might be why...

A DisplayObject's stage property ONLY is only available if the object in question has been added to the display list (i.e. addChild( MyClass ); ). There is another gotcha here though: if the parent class hasn't been added to the display list, the child class won't have been added either. Also, you'll notice in the example above that the stage.stageWidth property is being requested in the constructor. Even if the parent class immediately adds the child class to the display list, it will be done after the constructor has been called. Because of this, the code above will never work.

Imagine a class structure like this:

stage -> DocumentClass <-[addChild()] MyParentClass (MovieClip) <-[addChild()] MyFirstClass (Sprite) <-[addChild()] MySecondClass (Sprite)

If MyClass references stage, but MyParent isn't added to the display list (addChild()), the link between the stage and the class requesting the stage object is broken, so it will be null.

If, however, all of the classes are added to the display list BEFORE an attempt is made to access the stage property, all of the classes in the above example would be able to successfully access their respective stage properties.

So, wait until an object is in the display list before accessing stage, and don't access stage in the constructor.

More about this on FlexDeveloper.eu

Keywords for this post: flash, actionscript 3, stage, flex, display list, DisplayObject