我开始制作一个flash flash em-up游戏教程,我完成了它Asgamer Shoot em upp Game
现在我开始创建一个新的.fla,它是主菜单,我有一个播放按钮,所以当我按下它将加载.swf(游戏swf),但当我按下按钮时,我得到以下错误。
TypeError: Error #1009: Cannot access a property or method of a null object reference.
-at com.senocular.utils::KeyObject/construct()
-at com.senocular.utils::KeyObject()
-at com.actionscript.Ergasia::Ship()
-at com.actionscript.Ergasia::Engine()
public function Engine() : void {
if(stage) {
initialize();
} else {
addEventListener(Event.ADDED_TO_STAGE,initialize);
}
}
private function initialize(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE,initialize);
// here goes the code that's currently in Engine constructor
}
编辑:感谢Viper解决这个问题!
答案 0 :(得分:0)
将Engine
构造函数更改为以下内容:
public function Engine() {
if(stage) {
initialize();
} else addEventListener(Event.ADDED_TO_STAGE,initialize);
}
private function initialize(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE,initialize);
// here goes the code that was in Engine constructor
trace(stage);
ourShip = new Ship(stage);
stage.addChild(ourShip);
ourShip.x = stage.stageWidth / 2;
ourShip.y = stage.stageHeight / 2;
ourShip.addEventListener("hit", shipHit, false, 0, true);
stage.addChild(ourShip);
scoreHUD = new ScoreHUD(stage);
stage.addChild(scoreHUD);
for (var i:int = 0; i < numCloud; i++)
{
stage.addChildAt(new Cloud(stage), stage.getChildIndex(ourShip));
}
for (var b:int = 0; b < numStar; b++)
{
stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
}
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
主要问题是,Engine
类的编写假设stage
已经可以访问,但是当您加载SWF时,其stage
为空,而未添加该SWF到了舞台。为了避免这种情况,常见的做法是使用Event.ADDED_TO_STAGE
侦听器,并开始将代码放在那里而不是构造函数。