Search code examples
actionscript-3actionscriptstage

ActionScript 3.0 stageWidth in custom Class


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.

Solution

  • 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.