Skip to main content
Known Participant
March 8, 2011
Question

Creating a new instance with the same variable reference

  • March 8, 2011
  • 1 reply
  • 511 views

There´s any need to set to null a reference in this case?

private function initGame():void{

var game:Game = new Game()

}

private function endGame():void{

removeChild(game)

//here, should I set game to null?

}

then, to start a new game:

initGame()

In this case, do I need to set game to null at endGame? Or by adding a new game instance to game variable, the previous instance has no more reference and so is eligible for garbage collection?

Thanks

This topic has been closed for replies.

1 reply

Inspiring
March 8, 2011

Hi,

in your example the game variable is local to the initGame method, but you should prepare your object to be GC i.e. stop all timers, unregister events etc. and remove all references to it.

so in endGame you would nullify variable (if it is a member of class holding methods from example) as removing from stage doesn't remove it from memory and is not sufficient for GC.

Known Participant
March 8, 2011

Sorry, "game" it´s to be a global (class scope) variable, now I´ve fixed

private function initGame():void{

game = new Game()

}

private function endGame():void{

removeChild(game)

//here, should I set game to null?

}

then, to start a new game:

initGame()

I just want to know if the first instance of Game will be eligible for garbage collection after calling initGame again.

If there´s need to set "game" to null in endGame function, so when I create a new instance of Game the previous instance will be eligible to garbage collection.

I think, there´s no need to set to null, once, "game" variable will be reference to the new instance, and, then, the first instance of Game created will have no more references (because "game" is the only variable reference to the instance), and then, becomes eligible for garbage collection.

I also think, that, there would be no need to nullify game in endGame,  and, in any case, once, game is a global reference of a Game instance, and being that, the game variable will always be needed in the game´s file.

Well, thinking better, maybe it´s not even a good way to restart a game making a new instance of Game.

Maybe Game class should have a restart game function.

What would be the best method?

Thanks