I made a game in AS3 and i have 2 as file. One is HWMain and HWGame. When i click start button the script is switch from HWMain to HWGame but i got this error.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at HWGame()
at MethodInfo-26()
at MethodInfo-25()
Here's my code.
public class HWGame extends MovieClip
{
var INIT_STATE:String = "INIT_STATE";
var READY_STATE:String = "READY_STATE";
var PLAYER_STATE:String = "PLAYER_STATE";
var PLAY_STATE:String = "PLAY_STATE";
var END_STATE:String = "END_STATE";
var gameState:String;
//And another variable
public function HWGame()
{
gameState = INIT_STATE;
trace(gameState);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
function gameLoop(e:Event):void
{
switch (gameState)
{
case INIT_STATE :
initGame();
break;
case READY_STATE :
ready();
break;
case PLAYER_STATE :
startPlayer();
break;
case PLAY_STATE :
playGame();
break;
case END_STATE :
endGame();
break;
}
}
function initGame():void
{
//I write the long code
}
function ready():void
{
//I write the long code
}
function startPlayer():void
{
//I write the long code
}
function playGame():void
{
//I write the long code
}
function endGame():void
{
//I write the long code
}
}
}
I try to fixed it and i think the error is at gameState = INIT_STATE. What should i do?
Thanks.
From what you've cited, it's likely that your HWGame
instance has not yet been added to the display list; therefore, stage
is null
when you call:
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
Before accessing stage
, you could wait until added to stage:
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class HWGame extends MovieClip
{
var INIT_STATE:String = "INIT_STATE";
var READY_STATE:String = "READY_STATE";
var PLAYER_STATE:String = "PLAYER_STATE";
var PLAY_STATE:String = "PLAY_STATE";
var END_STATE:String = "END_STATE";
var gameState:String;
public function HWGame()
{
gameState = INIT_STATE;
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
protected function addedToStageHandler(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
}
protected function gameLoop(e:Event):void
{
switch (gameState)
{
case INIT_STATE:
initGame();
break;
case READY_STATE:
ready();
break;
case PLAYER_STATE:
startPlayer();
break;
case PLAY_STATE:
playGame();
break;
case END_STATE:
endGame();
break;
}
}
protected function initGame():void
{
//I write the long code
}
protected function ready():void
{
//I write the long code
}
protected function startPlayer():void
{
//I write the long code
}
protected function playGame():void
{
//I write the long code
}
protected function endGame():void
{
//I write the long code
}
}
}