When does stage get loaded?

I'm building a project in Adobe Flash Professional CS5 (using ActionScript 3.0).

In one of the classes, I want to add some objects to the scene based on the size of the scene.

I'm using the following code in the constructor:

stageWidthint = stage.stageWidth;
stageHeightint = stage.stageHeight;
startMenu.x = stageWidthint / 2;
startMenu.y = ((stageHeightint / 2) - 40);
instructionsMenu.x = stageWidthint / 2;
instructionsMenu.y = ((stageHeightint / 2) + 2);
highscoreMenu.x = stageWidthint / 2;
highscoreMenu.y = ((stageHeightint / 2) + 44);
quitMenu.x = stageWidthint / 2;
quitMenu.y = ((stageHeightint / 2) + 86);
this.addChild(startMenu);
this.addChild(instructionsMenu);
this.addChild(highscoreMenu);
this.addChild(quitMenu);

I'm getting a null reference on stage . After a quick search I found out stage is not yet loaded at that time. Still, I'd like to add those childs to the class. When does the stage get loaded? How can I solve this problem and still show all the stuff when the game starts?


在构造函数中使用ADDED_TO_STAGE事件。

 public function ConstructorName():void 
 {
     addEventListener(Event.ADDED_TO_STAGE,onAddedToStage); 
 }

 private function onAddedToStage(e:Event):void 
 {   
      removeEventListener(Event.ADDED_TO_STAGE,onAddedToStage);
      // add init code here
 }

我不确定在使用场景时情况如何,但您可以尝试:

package  {
  import flash.display.*;
  import flash.events.*;


  public class Test extends MovieClip {


    public function Test() {
      if (stage) {
        init();
      } else {
        addEventListener(Event.ADDED_TO_STAGE, init);
      }
    }

    protected function init(event:Event = null):void {
      trace("init");
      if (event) { removeEventListener(Event.ADDED_TO_STAGE, init) };
      //your code here
    }
  }
}

The Stage object is not globally available.
A class that extends a MovieClip will have a property "stage"(lowercase)
The "stage" property is null until the instance of your class has been added to stage.
That is why we listen for the ADD_TO_STAGE event.

There are work-arounds to stage = null one of which would be to pass in the stage as a parameter in the constructor IE: var xxx:MyClass = new MyClass(stage); That is if the class creating the instance already has a reference to stage.

I would like to add that accessing stage in your custom class is not a good OOP practice since classes should be only concerned with themselves . What I would suggest is overriding the width setter/getters. This is because sizing can change for example landscape to portrait rotation.

链接地址: http://www.djcxy.com/p/48268.html

上一篇: 使用swc编译IntelliJ flash慢

下一篇: 舞台什么时候加载?