LibGDX: is it better to reuse screens or create new instances every time?

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

  • MainMenuScreen
    • There is a Start button to switch to GameScreen. Also allows the player to change the basic settings of the game.
  • Gamescreen
    • The actual game for the game (where the playerโ€™s character is running and jumping).
  • GameOverScreen
    • A screen that plays the animation and then displays a menu that allows the player to restart the game (i.e., switch to GameScreen) or return to the main menu (i.e. switch to MainMenuScreen).

Am I better off storing my screens in variables and reusing them when switching screens, or is it better to delete each screen when I finish with it, and then create a new instance of the screen type that I intend to switch to?

And will the answer be different if the screen switching is more frequent (for example, between the Overorld screen and the battle screen in the game, for example Final Fantasy or Pokemon)?

Thanks!

+5
source share
1 answer

In my opinion, you should reuse Screen s, which are often used and position and recreate Screen , which are often not used.
In your example, all GameScreen , GameScreen , and MainMenuScreen must be reused, as they are directly related to each other:
As soon as the player starts the game, it is possible that he is dying. Then, GameOverScreen displayed, and immediately after that, MainMenuScreen displayed. Therefore, the user does not need to switch to these Screen manually.
Instead, OptionsScreen could be disposed of and recreated every time, because usually you open OptionScreen only a few times. It is also not directly related to other Screen , but the user needs to "force" the game to open OptionScreen . But while there are not many Screen s, reuse should not be a problem.
In the second example, Screen used more often, so they need to be reused.

EDIT:
As mentioned in @EssEllDee, you should also use hide() and show() . These methods are called by Libgdx when you switch Screen , and they can be used to delete / recreate heavy resources. For example, you can use the Texture used for the game when you switch to GameOverScreen and reload them when you switch to GameScreen .

+5
source

Source: https://habr.com/ru/post/1247325/


All Articles