Skip to content

Asset Management

miguel edited this page May 10, 2020 · 11 revisions

Asset Management has been taken to the next level in braingdx. On an average gamejam, developers do spend quite some time on setting up assets and accessing them via the AssetManager in libgdx. However, this can introduce lots of boilerplate code, since you have to load all your assets in beforehand. This is where a so called GameAssetLoader comes into play:

public class MyAssetLoader implements GameAssetLoader {

   @Override
   public void put(Map<String, Class<?>> map) {
      map.put("player.png", Texture.class);
   }
}

braingdx will automatically pick up the assets defined and load them for you. Make sure to provide your asset loader within the BrainGdxGame class:

public class MyGame extends BrainGdxGame {

    @Override
    protected GameAssetLoader getAssetLoader() {
	return new MyAssetLoader();
    }

    /** rest of the class **/
}

Automatic Asset Loading

The current approach allows us to automate things where needed. As a developer on a game jam I do not want to care about registering my assets. Ideally, the workflow should look like this:

  1. move asset into /assets folder
  2. define asset constant
  3. use your asset straight away This is possible with the so called SmartAssetLoader introduced in 0.1.0.

Defining asset constants

Create a new interface called Assets which looks like this:

public interface Assets {
   interface Textures {
      String PLAYER = "player.png";
   }
}

Enabling smart asset loading

this feature is not available for HTML projects!

After doing that you simply enable smart asset loading within your BrainGdxGame class:

public class MyGame extends BrainGdxGame {

    @Override
    protected GameAssetLoader getAssetLoader() {
	return new SmartAssetLoader(Assets.class);
    }

    /** rest of the class **/
}

braingdx will automatically pick up your assets and load them respectively. braingdx knows how to translate assets into Java objects (e.g. Texture, Music, Sound, TiledMap) by looking for @AssetSource annotations.

Doing that allows you to load custom asset types by defining them inside your Assets interface:

public interface Assets {

   @AssetSource(directory = "textures", assetClass = Texture.class)
   interface Textures {
      String PLAYER = "player.png";
   }

   @AssetSource(assetClass = CustomType.class)
   interface CustomType {
      String CUSTOM_ASSET = "asset.custom";
   }

   @AssetSource(assetClass = FreeTypeFontGenerator.class)
   String MY_FONT = "font.ttf";

   /** more assets defined below **/
}

Read more on this article how to register custom assets in libgdx.

Accessing smart loaded assets

In order to access an asset, simply do the following:

Texture playerTexture = Asset.get(Assets.Textures.PLAYER, Texture.class);
Clone this wiki locally