views:

1322

answers:

3

How do I access Stage Class properties in Costum Class?

Class:

package {
    import Main;
    import flash.events.*;
    import flash.display.Sprite;
    import flash.display.Stage;

    public class Run extends Sprite {
     var obj:a1_spr;


     public function Run() {
      runAssets();

     }



     private function runAssets():void {
      obj = new a1_spr()
      addChild(obj);
      obj.x = stage.stageWidth/2;

     }
    }
}

Output:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
+2  A: 
this.addEventListener(Event.ADDED_TO_STAGE, handleAdedToStage)

private function handleAddedToStage(event:Event):void
{
    this.runAssets()
}

private function runAssets():void
{
    obj = new a1_spr();
    addChild(obj);
    obj.x = this.stage.stageWidth/2;
}

You aren't going to have access to the stage in the constructor (unless you inject the stage into the class). Sprite has a stage property.

Joel Hooks
Tank You. It works. But I'm not sure I understand why. Can you please explain why I have to run it with listener?
dd
The stage property of all DisplayObjects is null untill they are added to the display list, so you need to make sure the object is in it before trying to access it ;)
Cay
When you instantiate your Object with var myObject:MyObject = new MyObject() the constructor is run immediately, including any methods you call inside of the constructor as well. Even if the next line after the new MyObject is addChild(myObject) the myObject is not going to be on the stage, or have reference to the stage. You COULD also make stage:Stage a constructor argument of MyObject, so new myObject(this.stage), and you would have immediate access to the application's stage.
Joel Hooks
+3  A: 

Hey,

To expand on what Joel said, and put it into context:

Every display object has a .stage property, but that property is null until you add you display object onto the display list. So during construction, you will never be able to access it, (because it gets added afterwards)

The event ADDED_TO_STAGE gets fired when you add your object to the stage, ltting you know that the .stage property is now populated. After that happens you can access the stage from anywhere in you object.

Hope that clarifies things for you.

Tyler Egeto
A: 

when flash compiles the fla assets with your .as files, there's no stage. so the code is initiated as preparation for your documentclass, you have to listen to if there's a stage so it can be rendered.

that's why you listen to ADDED_TO_STAGE , to check it's actually in the display list.

This problem occurs for all display objects, since they must be added to the display list when there's an actual stage.

get used to add that listener, and check for a stage. specially when working in a team and your doing your own components in a larger project.

martinlindelof