Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libGDX: is it better to re-use Screens or create new instances every time?

Tags:

java

libgdx

Here's my case. I have three different types of screens:

  1. MainMenuScreen
    • Has a "Start" button for switching to the GameScreen. Also lets player change basic game settings.
  2. GameScreen
    • The actual playable game (where the player character runs and jumps).
  3. GameOverScreen
    • Screen that plays an animation and then displays a menu that lets the player start the game again (i.e. switch to GameScreen) or return the main menu (i.e. switch to MainMenuScreen).

Am I better off storing my Screens in variables and reusing them when I switch screens, or is it better to dispose of each Screen when I'm done with it and then create a new instance of the screen type I intend to switch to?

And would the answer be different in a case where Screen switching is more frequent (like between an overworld Screen and a battle Screen in a game like Final Fantasy or Pokemon)?

Thanks!

like image 957
hithere Avatar asked Apr 18 '16 02:04

hithere


1 Answers

In my opinion you should reuse Screens, which are used frequently and dispose and recreate Screens not used that often.
In your example the GameScreen, GameOverScreen and MainMenuScreen should all be reused, as they are directly connected to each other:
As soon as a player starts a game, it is possible, that he dies. Then the GameOverScreen is shown and directly after that the MainMenuScreen is shown. So the user does not need to switch to those Screens manually.
The OptionsScreen instead, could be disposed and recreated every time, because usualy you open the OptionScreen only a few times. Also it is not directly connected to any other Screen, but the user needs to "force" the game to open the OptionScreen. But as long as there aren't too many Screens, reusing shouldn't be a problem.
In your second example, the Screens are used even more often, so they definitly should be reused.

EDIT:
As @EssEllDee mentioned, you should also make use of hide() and show(). Those methods get called by Libgdx, when you switch the Screen and they can be used to dispose/recreate heavy ressources. For example, you might dispose Textures used for the game, when you switch to the GameOverScreen and reload them, when switching to the GameScreen.

like image 172
Robert P Avatar answered Oct 24 '22 23:10

Robert P