I have the following two classes:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var test:NewClass = new NewClass();
}
}
}
AND
package
{
import flash.display.Sprite;
public class NewClass extends Sprite
{
public function NewClass()
{
trace(stage.width);
}
}
}
I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at NewClass()[C:\Documents and Settings\Roma\poo\src\NewClass.as:10]
at Main/init()[C:\Documents and Settings\Roma\poo\src\Main.as:23]
at Main()[C:\Documents and Settings\Roma\poo\src\Main.as:15]
Why???
yeah, a flash develop user … 😀
uhm, the reason is: the stage is only available to objects, that are on the display list …
modify your class as follows:
and Main::init as follows:
oh, and you can change your
Coding Style TypefromBraceAfterLinetoBraceOnLineinTools > Program Settings > FlashDevelop > Indenting, just in case you are inclined … 😉edit:
if you want to access the stage, within the scope of a
DisplayObject, you need to be sure, the stage is available to it … if you want to access the stage as soon as possible, then you will need the trick provided … but if you access the stage within a click handler for example, this automatically implies theDisplayObjectis on the display list … it couldn’t be clicked otherwise …a little note though: i don’t think, it’s particularly clever to access the stage from everywhere … when it comes to display, your app hierarchy should follow the display list hierarchy, i.e. access goes from the root down the branches, and not the other way round … this is important to achieve reusability …
greetz
back2dos