javalibgdxloadingassets

How can I query the name of the currently loading asset in LibGDX?


I am using LibGDX's AssetManager like this in my create() method:


ASSETS = new AssetManager();
FileHandle assetHandle = Gdx.files.internal("assets.txt");
String text = assetHandle.readString();
String[] lines = text.split("\n");
for (String line : lines) {
    
    ASSETS.load(line, Texture.class);

}

In my render() method I want to be able to output/query the name of the asset i am loading, such as

if (!ASSETS.update()){
    System.out.println("Currently Loading" + assetName);
}

Is there a way to do this, as we can already query the progress, or would I manually have to guess which asset is loading?

I have tried the .peek() method such as this:

String currentAsset;
    try{ //the first frame is "peeking" an empty array

        currentAsset = ASSETS.getAssetNames().peek(); 


       } catch (Exception e){
           currentAsset="Unknown";
       }

System.out.println("Loading asset: " + currentAsset);

Which appears in the console to output only around 5-10 unique names, even though my assets.txt has around 1000 entries.


Solution

  • The AssetManager does expose what it is about to load, but you can find out what it just has loaded (by jumping through some hoops).

    If you want to use peek on AssetManager.getAssetNames() you can, but you need to keep track of the loaded items yourself, as the getAssetNames returns the keys of a ObjectMap and that is not ordered. You can do that by sor

    ObjectSet<String> loadedAssets = new ObjectSet<>();
    
    ...
    
    if (!ASSETS.update()) {
       var assetManagerAssets = ASSETS.getAssetNames();
       for(var name : assetManagerAssets) {
          if (!loadedAssets.contains(name)) {
             // Consider name as just have been loaded, print it or display it or whatever
          }  
       } 
       loadedAssets.addAll(assetManagerAssets);
    }
    

    You can also utilize the fact that AssetManager logs whenever it has loaded an asset. By setting a logger where you override the info(String message) method you can intercept it:

    ASSETS.setLogger(new Logger("", Logger.INFO) {
        @Override
        public void info(String message) {
           // Message contains the loaded resource, you might need to do some string parsing 
        }
    } 
    

    This will catch things about to be loaded.