javaandroidlibgdxassetsasset-management

How to handle AssetManager in multiple screens


public static AssetManager assets = new AssetManager(); should be avoided, however how do I handle an AssetManager in multiple screens? Is this a good solution?

public class myGame {

   assetMananger manager = new AssetManager(); 
   ...
   public assetManager getAssetMananger(){
      return manager; 
   }
}

public class GameScreen implements Screen{

    private AssetManager manager;

    public GameScreen(myGame game){
       manager = game.getManager();
    }

    public void render(){
        manager.load(...);
    }

Solution

  • Gdx.app.getApplicationListener() return ApplicationListener instance. You can typecast to your implemented class and then easily access any method or data member of that class.

    In this way :

    ((GdxTest)Gdx.app.getApplicationListener()).assets  // <-- You can use from where you want in your project. 
    

    ApplicationListener implemented class :

    public class GdxTest extends ApplicationAdapter {
    
        public Assets assets;
    
        @Override
        public void create() {
    
            assets= new Assets();
        }
    
        ....
    
        @Override
        public void dispose() {
           assets.dispose();
        }
    }
    

    Assets class that handle all assets/resources of Game

    public class Assets implements Disposable {
    
        public AssetManager assetManager;
    
        public Assets(){
    
            assetManager=new AssetManager();   
        }
    
        ...
    
        @Override
        public void dispose() {
            assetManager.dispose();
        }
    }