舞台何时加载?
我在Adobe Flash Professional CS5中构建项目(使用ActionScript 3.0)。舞台何时加载?
在其中一个类中,我想根据场景的大小向场景添加一些对象。
我使用构造函数中的以下代码:
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);
我得到的stage
空引用。经过快速搜索,我发现当时尚未加载stage
。不过,我想把这些孩子加入课堂。舞台什么时候加载?如何解决这个问题,并在游戏开始时仍显示所有内容?
在构造函数中使用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
}
你知道舞台完成加载的时候吗?在阶段实际加载之前,但在代码开始运行之后,哪些类型的东西被执行? – Joetjah 2013-03-12 14:44:45
当你的主类收到ADDED_TO_STAGE时,舞台完成加载,我并不真正了解flash播放器的内部结构以及之前的操作。但是您并不需要这些知识,只要注意,对于不在舞台上并且在收到ADDED_TO_STAGE事件之前的显示对象,舞台成员将为空。 – 2013-03-12 14:59:11
好的,我明白了。我希望通过拆分我的构造函数来提高性能,但似乎没有人知道在其中可以做些什么。似乎我必须通过试验和错误来找到它;) – Joetjah 2013-03-12 15:00:58
我不知道使用的场景时,是如何工作的,但你可以尝试:
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
}
}
}
的Stage对象不是全局可用。
扩展MovieClip的类将具有属性“stage”(小写)
在您的类的实例已添加到舞台之前,“stage”属性为null。
这就是为什么我们要监听ADD_TO_STAGE事件。
stage = null其中的一个将在构造函数IE中作为参数传递到舞台中:var xxx:MyClass = new MyClass(stage); 这就是说,如果创建实例的类已经有阶段的引用。
我想补充说,在你的自定义类中的访问阶段不是一个好的面向对象的实践,因为类应该只关心自己。我会建议重写宽度setter/getters。这是因为尺寸可以改变,例如风景到人像旋转。
Event.ADDED_TO_STAGE – 2013-03-11 20:17:20
好的,谢谢,这解决了我的问题。我将所有这些东西放在事件处理程序调用的方法中。但是,什么时候加载完成?这是几秒钟或什么事情? – Joetjah 2013-03-11 20:24:27
Downvoter,关心发表评论? – Joetjah 2013-03-12 14:44:03