AS3 - Access MovieClip from stage within a class

坚强是说给别人听的谎言 提交于 2019-12-24 16:42:30

问题


I have been stuck on this for a long time and have looked at past questions on here about this similar issue such as this post: How do I access a movieClip on the stage using as3 class?.

I use the constructor to listen for the ADDED_TO_STAGE event, and then initiate the main function to set up the eventListeners from the ADDED_TO_STAGE handler. Within the same handler I also try to get a MovieClip from the stage using the following code:

player = stage.getChildByName("player") as MovieClip;

player is defined globally as a MovieClip.

Within another handler (after the class has been added to the stage) I set the player to go to an particular frame label using player.gotoAndStop("jump");. However an output warning shows up saying "Cannot access a property or method of a null object reference".

Here is the code which I use:

public var player:MovieClip;

public function PlayerControl():void {      
    this.addEventListener(Event.ADDED_TO_STAGE, addedToStage);          
}

private function addedToStage(event:Event):void{
    removeEventListener(Event.ADDED_TO_STAGE, addedToStage);

    this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);

    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

    stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

    player = stage.getChildByName("player") as MovieClip;

}

private function enterFrameHandler(event:Event):void{   
   if(up == true && moviePlaying == false){
      player.gotoAndStop("jump");
      moviePlaying = true;
   }
}

来源:https://stackoverflow.com/questions/17999074/as3-access-movieclip-from-stage-within-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!