addChild custom class AS3
This is the class I am trying instantiate into my main class:
public class Character extends Sprite {
[Embed(source='../lib/front1.svg')]
private var front1Class:Class;
private va开发者_如何学Cr 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;
}
}
When I set it to the document class, it works fine.
However... when I make THIS my document class and try to call it from there:
public class Shell extends Sprite
{
private var character:Sprite = new Character ();
public function Shell()
{
addChild(character);
}
}
It breaks, and no longer shows the sprite object (though it does erase the mouse pointer).
What's the deal here? You can't instantiate custom sprite or movieclip classes into a DisplayObject class???
The stage is null
in the constructor. That only works when your class is the Document Class, as you found out yourself. So change your constructor like this:
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);
}
Adding the listener will access the stage only after the stage is known, and it's no longer null
精彩评论