Loading and tracking assets

After making our assets, the next step is to allow our game to use them and load the texture atlas. Loading an asset such as a texture can be as simple as the following line of code:

    Texture texture = new Texture(Gdx.files.internal("texture.png"));

In the preceding example, we ask LibGDX to get an internal file handle to the texture.png file. Invoking an internal file means that LibGDX has to resolve the file's path by scanning the assets folder of the game. Then, the handle is passed over as an argument to the constructor of the Texture class to instantiate a new object of this type. This texture instance can now be directly rendered to the screen with another line of code, as shown in the following listing:

    batch.draw(texture, x, y);

Obviously, working with assets is basically very easy. However, this matter becomes a lot more complicated when we want to use several assets. It gets even worse if we want to run the game on Android. As we have learned in earlier chapters, there are pause and resume events that might involve a so-called context loss. When a context loss occurs on Android, it means that the operating system has decided to forcefully free the memory that was occupied with your loaded assets. Therefore, directly accessing your assets after a context loss would immediately crash the resumed game. To prevent these crashes, you need to reload your assets before accessing them again. Furthermore, you should always free the memory when your game is no longer using a certain asset by calling its dispose() method, as shown in the following listing:

    texture.dispose();

You probably already guessed that this is not going to be much fun as you have to worry about all the housekeeping to load, reload, and unload while using lots of assets, especially as these actions will add up very quickly with each new asset that will be used. This is one of the reasons why LibGDX provides a manager class for this task, which is called AssetManager. It allows you to delegate the work of keeping a list of the loaded assets to the manager. The manager is also able to asynchronously load new assets, which simply means that loading is done in the background and therefore does not stop the updating and rendering to the screen. This is a very useful functionality; for example, it allows you to render and update a progress bar that shows the current loading status. Nonetheless, the actual loading of our assets still has to be done on our own. For this reason, we are going to create our own Assets class, which will also help us structure our loaded assets in logical units and make them accessible from everywhere in the game code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset