Search code examples
javalibgdx

Best way to handle sprites in games with different screens in libgdx


Another day, another problem.

I have a sprite which has fields such as livesRemaining.

Let's say in the main game screen I fall off and I switch the screen to a "Lives Remaining" screen using the setScreen method. My problem is that the livesRemaing field is now lost.

My question is what is the best way to handle these "global game variables" which should be transition between screens.

Should I:

  1. Create one sprite in the game class and pass this to the different screens?
  2. Create a new sprite every screen and keep the "global game variables" in the main Game class?

I'm not sure if there is a best approach to this or if it is just a matter of taste.

Any suggestions would be appreciated.

Thanks in advance!


Solution

  • Using cache is good to avoid objects creation/destruction (that are expensive on java due to garbage collector on a "real time" game). It seems that you need a better data structure to handle all the game design to avoid that problems. Your option 1 is the closest approach to be a good one, but it depends on the general design.