[LibGDX] Managing Screens

I am in two minds on how to handle this, I am working on a little manager class that controls game state and screens and just wondering if it is a bad idea to keep screens in memory?

Basically if the user clicks play on the main menu, game state changes and screen is changed to play, but main menu is kept in memory for later.

Is this a bad idea? Should I just init the screen all over again? Obviously the game screen would have to be recreated or else it would start off at wherever the game was last.

But is it ok to keep a reference to other screens?

[quote=“Gibbo3771,post:1,topic:46717”]
There is no probem with that as long as your screens do not do something exceptional that requires a huge load of memory. Just don´t update them. I use a Stack of screens in which I just update the topmost one. Its nice & simple, and works like a charm.

[quote=“Grunnt,post:2,topic:46717”]

Hm right at the moment I only have 3 screens, MainMenu, Options and Play. They will be stored within a nested inner class in the Manager class, any other way you recommend in doing this?

I simply pass the Manager into pretty much every constructor that requires it, so anything that can alter the game state or screen.

Here’s rougly what I did (dont have the code with me right now, so its much simplified):

public class Game {
	public Stack<AbstractScreen> screens

	public void update(float delta){
		screens.peek().update(delta);
	}

        public void init(){
		screens.push(new MenuScreen());
        }
}

public abstract class AbstractScreen {
	protected Game game;

	public AbstractScreen(Game game) {
		this.game = game;
	}
	
	public abstract void update(float delta);
}

public class MenuScreen extends AbstractScreen {
 
	// ... constructor stuff

	public void update(float delta){
		if (playButtonIsPressed){
			GameScreen gameScreen = new GameScreen();
			game.screens.push(gameScreen);
		}
	}
}

So essentially any screen that is pushed on top is instantiated anew, and any screen that is deactivated is removed from the stack and garbage collected. Try to design your game in such a way that screens do not (or as little as possible) reference to each other.

Best make the screens in seperate files / classes, and not as inner classes; its much easier to keep an overview this way instead of when you put everything in one Huge Messy Class.

Yeah my screens are in seperate classes but the Manager class has a ScreenManager class nested inside it that simply holds reference to the screens.

Ah cool, then we’re takking pretty much the same approach.

Yeah looks like it, only problem with this is that my main menu and stuff will have animations so I will have to reset everything, probably faster trashing it and re-creating it lol.