AS3 | 1120: access to properties step undefined

My goal is to create a rectangle like MovieClip with the size of the scene, but Flash gives me this error:
1120: Access to undefined properties. (on line 6, 7, 14)

My code is:

package {
    import flash.display.MovieClip;

    public class main {
        var mc_background:MovieClip = new MovieClip();
        var stageW:Number = stage.stageWidth;
        var stageH:Number = stage.stageHeight;

        public function main() {
            drawBackground();
        }

        public function drawBackground():void {
            mc_background.beginFill(0xFF00CC);
            mc_background.graphics.drawRect(0,0,stageW,stageH);
            mc_background.graphics.endFill();
            stage.addChild(mc_background);
        }

    }
}
+4
source share
2 answers

The property of the stageobject is not defined until the object is added to the scene or other object in the workspace.

, , , . , , , stageW stageH.

stage, , ADDED_TO_STAGE:

package {
    import flash.display.MovieClip;
    import flash.events.Event;

    public class main
    {
        var mc_background:MovieClip = new MovieClip();

        public function main()
        {
           addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
        }

        private function addedToStageHandler(event:Event):void
        {
            // Generally good practice to remove this listener from the object now because it stops addedToStageHandler from being called again if the object is removed and added back to the stage or display list.

            removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);

            drawBackground();
        }

        private function drawBackground():void {
            mc_background.beginFill(0xFF00CC);
            mc_background.graphics.drawRect(0,0,stage.stageWidth, stage.stageHeight);
            mc_background.graphics.endFill();
            addChild(mc_background);
        }
    }
}
+1

, , , , . :

protected function addedToStageHandler(event:Event):void
{
     //do stuff
}

protected funcion init():void
{
    addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
    //more stuff
}

,

+4

Source: https://habr.com/ru/post/1540214/


All Articles