Attaching vs. initializing a state

I have a MainState that runs the main part of my game. In my initialize() method, I include the code to import all the world assets, load the HUD, etc. I expect that this code should only run once.



Then, I have a PauseState that will freeze whatever is going on in MainState and then the player can quit or resume, etc. So I detach the MainState and then attach the PauseState. This works as expected as the MainState no longer updates.



Then, let’s say the user wants to resume. So I detach the PauseState and attach the MainState. I expect the stateAttached() method to be called but not the initialize() method, since that was already called once. But instead, initialize() is called again, so the world assets are loaded again and the camera is reset. Instead, I want the game to “unfreeze” instead of reinitializing everything.



Is this the intended function of AppStates? If so, what is the difference between initialize() and stateAttached()? Should I instead put my “initialization” code in a constructor so it only runs once? (I have only one MainState as an object that I use but I create new PauseStates as needed).

stateAttached is run on the thread that you call attach() on (and almost never useful). initialize() is always called on the OpenGL thread.



In general, initialize() should setup everything about the app state and cleanup() should clean it up. These are both run on the OpenGL thread.



The problem here is that you are detaching the state (which should cause it to fully cleanup ready for a new initialize() later) instead of just pausing it. Just setEnabled(false) on the state to pause it. It will stop having its update() method called.



If people don’t write their states this way then they open themselves up to leaks. cleanup() should remove all traces that the state was ever there. initialize() should always then be called post-attach. A state that is not attached cannot be initialized… by definition.