Question

My goal is to create rectangle as MovieClip with stage size, but Flash gives me this error:
1120: Access of undefined property stage. (on line 6,7,14)

My code:

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);
        }

    }
}
Was it helpful?

Solution 2

The stage property of an object isn't defined until the object has been added to the Stage or another object on the Stage.

The constructor of a class is called when the class instance is created, and that is before the instance could have been added to the Stage. So, you can't access stage within code you call from the constructor, or when you define the instance variables stageW and stageH.

To access the stage property as soon as the object is added to the stage, allow the object to handle the ADDED_TO_STAGE event:

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);
        }
    }
}

OTHER TIPS

i had a similar problem, the thing is, the stage hasn't really been setup yet, so you need to wait to get data from it or stuff in it. just add this:

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

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

hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top