0
votes

I am having some trouble figuring out the proper use of libGDX's AssetManager class. From what I understand, you are never supposed to create a static instance of an AssetManager. The alternative that people suggested was to pass around the AssetManager reference to every single class that uses it. I'm wondering if what I have proposed below is another safe alternative.

public class GdxGame extends Game {

    private AssetManager assets;

    ....dispose, create AssetManager etc


    public static AssetManager getAssets() {
        return ((GdxGame) Gdx.app.getApplicationListener()).assets;
    }
}

I really don't want to have to pass an AssetManager or an Assets class around to every single class in the game, so I'm trying to figure out a solution that allows some kind of static referencing. Is this safe?

1
How many classes do need access to your assets and why? It sounds like you are trying to solve the wrong problem. - Xoppa
I would think many. Every entity (human, zombie, explosion) will need to reference the class no? - matthewtory
You should only need direct access to your assets in a few classes. Your entities should only have to be provided a skin or atlas or regions or whatever you prefer, but certainly should not be responsible for accessing your AssetManager. You might want to reconsider your approach. Don't make game objects responsible for accessing assets, they should not need to care about that. - Xoppa
Perhaps they would not have direct access to the actual AssetManager class, but would they not need access to some sort of central asset bank to access their textures/animations? - matthewtory
No, there is no reason why a game object should be aware of its visual representation. If it's convenient for you to store that info along with the entity then you can certainly do that, but that doesn't make the entity responsible for that. You might want to read into object oriented design and separation of concerns if you want to read more about that. - Xoppa

1 Answers

0
votes

I think you worry too much :-) The static instance you suggested originally will be perfectly adequate and functional for your purposes:

private static AssetManager assets;
....dispose, create AssetManager etc

public static AssetManager getAssets() {
    return assets;
}

The only trap for young players to avoid is when you pause an Android app: on resume, just reload the AssetManager and its assets before continuing. Don't worry about semantics - if it works for you, then it's fine. Happy days :-).