What's happened to stage? Unravelling the display list
Posted: 19/01/08
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
Popular categories:
Recent posts:
- Mac OS find files using regex
- ADB device driver won't install
- Eclipse: An error has occurred. See the log file .metadata/.log
- Updated blinkbox iPad app
- Nexus 7 doesn't appear in adb devices list
- Improve the keyboard in the Samsung ICS update
- 403 Forbidden error on Mac web server
- Getting error with manually created NIB?
- Adding/removing items from PATH on Mac
- Presenting at Flash Oxford
- more...
Publications:
Places you'll find me:
Archive:
- April 2024
- March 2024
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- July 2023
- June 2023
- May 2023