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;
}
}