Flash addChild抛出一个异常
我正在做一个游戏。我在Flash中设计了一个进程条,并将其链接到AS 3。 在主类(main_c.as)中,我为阶段分配一个变量:Flash addChild抛出一个异常,flash,actionscript-3,actionscript,Flash,Actionscript 3,Actionscript,我正在做一个游戏。我在Flash中设计了一个进程条,并将其链接到AS 3。 在主类(main_c.as)中,我为阶段分配一个变量: package { import flash.display.MovieClip; import flash.display.Stage; public class main_c extends MovieClip { static public var stageRef:Stage; public var s:start_b; p
package {
import flash.display.MovieClip;
import flash.display.Stage;
public class main_c extends MovieClip {
static public var stageRef:Stage;
public var s:start_b;
public var bar:timer_bar;
public function main_c()
{
// constructor code
stageRef = stage;
s = new start_b();
addChild(s);
s.x = 260;
s.y = 225;
}
}
}
然后有一个start_b类,它创建一个按钮并单击以触发第三个类(game.as)的构造函数。以下是start_b的代码:
package {
import flash.display.SimpleButton;
import flash.events.MouseEvent;
public class start_b extends SimpleButton {
public var g:game;
public function start_b()
{
// constructor code
this.addEventListener(MouseEvent.CLICK, start_g);
}
public function start_g(e:MouseEvent):void
{
g = new game();
this.removeEventListener(MouseEvent.CLICK, start_g);
this.visible = false;
}
}
在最后一个类中,我想将状态栏添加到stage,但是当我运行时,我得到错误-
TypeError:Error#1009:无法访问空对象引用的属性或方法。
在游戏()中
开始时\u b/开始时\u g()
这是第三类(game.as)的代码:
如果你能帮助我,我将非常高兴:-)谢谢,祝你愉快 您需要检查您的舞台是否准备就绪: 主要承包商/建造商:
public function main_c()
{
if (stage)
{
init();
}
else
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
主/初始:
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
stageRef = stage;
s = new start_b();
addChild(s);
s.x = 260;
s.y = 225;
}
线索#1:
TypeError:错误#1009:无法访问空对象引用的属性或方法。在游戏开始时
这意味着游戏
构造函数中的某个对象为空,但您正试图访问该对象的成员函数或属性
分解它:
main_c.stageRef.addChild(bar);
points = 0;
time = new Timer(50);
time.addEventListener(TimerEvent.TIMER, flow);
time.start();
trace("d");
这里唯一可能的错误原因是第一行
main_c.stageRef.addChild(bar);
因此,解决这个问题的方法是查看main_c.stageRef
是否为空,并相应地采取行动
我的解决方案是:重新定义游戏类的构造函数:
public function game() {
init();
}
public function init() {
if(main_c.stageRef) {
//restartirane na igrata (nulirane)
main_c.stageRef.addChild(bar);
points = 0;
time = new Timer(50);
time.addEventListener(TimerEvent.TIMER, flow);
time.start();
trace("d");
} else {
callLater(init);
}
}
该方法的文档
另一个不相关的注意事项是,ActionScript类名按惯例以大写字母开头。这有助于将它们与以小写字母开头的实例名称区分开来。如果有人有解决方案,请编写:-)看起来您已经有了一些很好的答案,但关于良好的编码实践,请注意以下几点:1)类名应大写,并使用大写字母(与标准Flash库类的命名方式相同,例如:MovieClip)。因此,您的
timer\u bar
类应命名为TimerBar
,您的main\u c
类可能应命名为MainC
,等等。2)通常希望使用的名称至少比单个字符更便于人类阅读。您的行s=newstart_b()代码>的可读性要高得多,因为startBtn=newstartbutton()代码>。不管怎样,只是一些提示:)非常感谢,我会记住:-)你真的帮助了我,祝你有一个愉快的一天!Wellcome:)…如果答案对你的问题是正确的,那么一定要把它标记为接受。。还有其他好的答案,你可以给他们投票。顺便说一句,伊恩在评论中有一些好的建议。
public function game() {
init();
}
public function init() {
if(main_c.stageRef) {
//restartirane na igrata (nulirane)
main_c.stageRef.addChild(bar);
points = 0;
time = new Timer(50);
time.addEventListener(TimerEvent.TIMER, flow);
time.start();
trace("d");
} else {
callLater(init);
}
}