Home » Android » java – Proper way to dispose screens in Libgdx

java – Proper way to dispose screens in Libgdx

Posted by: admin June 15, 2020 Leave a comment

Questions:

What is the proper way of completely disposing of a screen in Libgdx? Currently If I click where a button was on my previous screen the button still does what it would of done if I were on that screen. Should I be .dispose()-ing everything I can in the dispose() method? or is there a simpler way to dispose of everything on screen?

How to&Answers:

Unfortunately there is no easier way. These classes do not share any kind of common “Disposable” interface, or anything like that, to do it automatically. Everything that has a dispose() method needs to be disposed manually when it’s not needed anymore.

This is also valid for the Screens themselves. When switching Screens they do not get disposed automatically, but you need to do that yourself (before calling Game.setScreen()).

On the other hand, this is not a big deal. Just look through everything in your Screen and check whether it has to be disposed or not. If there is a dispose method, call it in dispose() of the Screen.

BUT this does not explain your behaviour about invisible buttons from the last Screen. I suppose you use a Stage and used Gdx.input.setInputProcessor(stage);. This setting will not be changed when you change the screen and you have to set the input processor to the Stage of your current Screen, or to whatever that handles the input in your current Screen. That way the “old” stage will not catch any inputs anymore.

Answer:

I can confirm that this issue is not passing the inpur processor a new stage. this will result in “ghost” buttons as described.

Answer:

Unfortunately LibGDX API documentation says

Note that dispose() is not called automatically.

So what I do is disposing all disposables (such as Stage, Skin, Texture … etc) inside the hide() method in the Screen because hide() is called automatically and it works very well!

example:

public class GameScreen implements Screen {
...
    @Override
    public void hide() {
        mainStage.dispose();
        playGroundStage.dispose();
        controller.dispose();
        labelActor.dispose();
    }
...
}