我在做一个游戏。我已经在Flash中设计了一个进程栏,并将其链接到AS3。在主类(main_c.as)中,我为stage分配了一个变量:
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的状态栏进行addChild,但是当我运行时,我得到了错误-
TypeError: Error #1009: Cannot access a property or method of a null object reference. at game() at start_b/start_g()
下面是第三个类(game.as)的代码:
package{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import main_c;
public class game extends MovieClip {
public var points:Number;
public var ptw:Number;
public var time:Timer;
public var bar:timer_bar = new timer_bar();
public var cnt:main_c;
public function game()
{
//restartirane na igrata (nulirane)
main_c.stageRef.addChild(bar);
points = 0;
time = new Timer(50);
time.addEventListener(TimerEvent.TIMER, flow);
time.start();
trace("d");
}
public function flow(t:TimerEvent):void
{
//code
//bar.y++;
}
public function addPoints():void
{
//function code here
}
public function removePoints():void
{
//function code here
}
public function checkTime():void
{
//function code here
}
public function end():void
{
//function code here
}
}
}如果你能帮助我,我将非常高兴:-)谢谢,祝你愉快!
发布于 2011-12-01 06:19:12
您需要检查stage是否已准备就绪:
Main_c /构造函数:
public function main_c()
{
if (stage)
{
init();
}
else
{
addEventListener(Event.ADDED_TO_STAGE, init);
}
}Main_c / 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;
}发布于 2011-12-01 13:57:30
线索# 1:
TypeError:错误#1009:无法访问空对象引用的属性或方法。at game() at start_b/start_g()
这意味着game构造函数中的某个对象为空,但您正在尝试访问该对象的成员函数或属性。
拆分一下:
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);
}
}callLater方法的文档
在不相关的注释中,按照惯例,ActionScript类名称以大写字母开头。这有助于将它们与以小写字母开头的实例名称区分开来。
https://stackoverflow.com/questions/8331223
复制相似问题