Search code examples
javaandroidlibgdxassetsscene2d

Assets in Libgdx


This is my way to deal with assets

I have Assets class which has assetsManager and only Strings of files path

public class Assets {
    public static AssetManager manager = new AssetManager();
    public static final String background = "bg.png";
    public static final String menu = "menu/menu.atlas";

    public static Texture getTexture(String name) {
        return manager.get(name, Texture.class);
    }

    public static TextureAtlas getTextureAtlas(String name) {
        return manager.get(name, TextureAtlas.class);
    }

    public static void dispose() {
        manager.clear();
    }
}

In Screen I load Assets

public class MenuScreen implements Screen {
    public void show() {
        //load assets
        Assets.manager.load(Assets.background, Texture.class);
        Assets.manager.load(Assets.menu, TextureAtlas.class);
        Assets.manager.finishLoading();
    }
}

when I use them I do this

Texture background = Assets.getTexture(Assets.background);

I call dispose in Game Class only

public class GameMain extends Game{
    @Override
    public void dispose() {
        super.dispose();
        Assets.dispose();
    }
}

My question :

Is this a proper way to manage assets or am I doing anything wrong ?

Another question I have a stage (which have actors which use textureRegions)

In PlayScreen to dispose it(with its textures) I call stage.dispose() only

public class PlayScreen implements Screen{

@Override
    public void dispose() {
        stage.dispose();
    }
}

Is this proper or not ?


Solution

  • The usual way you don't make everything static. So remove every static keyword and put the AssetManager in your main class (which extends Game). Add a Getter for the AssetManager to your main class and pass a reference of your main class to every new Screen class you instantiate. So that the Screen (in your example named PlayScreen) can access the main class and it's AssetManager to load the Screen's assets.

    Also the AssetManager is meant to be asynchron, so if you call finishLoading() on it it will block the main thread until all assets are loaded. This is not a problem if you have not much to load but if a game gets bigger usually a splash screen is used and assets are loaded asynchronously in the background. See this libgdx wiki link for more information.

    Dispose your AssetManager in the main class (like you did). Dispose the stage AND the Screen's assets too in the Screen's dispose method. Check this link for a list of classes that need to be disposed manually (to prevent memory leaks).

    Also see this question for example code.