这是我尝试实例化到我的主类中的类:
public class Character extends Sprite {
[Embed(source='../lib/front1.svg')]
private var front1Class:Class;
private var crosshair:Sprite = new front1Class ();
public function Character() {
trace("started");
Mouse.hide();
crosshair.scaleX = 5;
crosshair.scaleY = 5;
this.addChild(crosshair);
stage.addEventListener(Event.ENTER_FRAME, MrEveryFrame);
stage.addEventListener(MouseEvent.CLICK, click);
}
private function click(evt:MouseEvent):void {
trace("clicked @ " + evt.stageX + "," + evt.stageY);
}
public function MrEveryFrame(e:Event):void
{
crosshair.x = mouseX - 15;
crosshair.y = mouseY - 15;
}
}
当我将它设置为文档类时,它可以正常工作。
然而......当我把它作为我的文档课并尝试从那里调用它时:
public class Shell extends Sprite
{
private var character:Sprite = new Character ();
public function Shell()
{
addChild(character);
}
}
它断开,不再显示精灵对象(虽然它确实擦除了鼠标指针)。
这是什么交易?您无法将自定义精灵或动画片段类实例化为DisplayObject类???
答案 0 :(得分:2)
构造函数中的阶段为null
。这只适用于您的类是文档类,就像您自己发现的那样。所以改变你的构造函数:
public function Character() {
trace("started");
Mouse.hide();
crosshair.scaleX = 5;
crosshair.scaleY = 5;
this.addChild(crosshair);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void
{
stage.addEventListener(Event.ENTER_FRAME, MrEveryFrame);
stage.addEventListener(MouseEvent.CLICK, click);
}
添加侦听器只有在知道舞台后才能访问舞台,并且不再是null