Managing ressources - OpenWeek/app-for-a-KAP GitHub Wiki

The AssetsManager

We decided to rewrite an assetsmanager ourself to get better control of it's actions. Let's see how it works.

The AssetsManager is a singleton which is in charge of managing resources and control, more particularly, that same resources aren't loaded twice in memory. Currently, the methods supported by the Assetsmanager consists of get and dispose functions. The following list shows which method is provided

Type Functions Type returned
Get getTextureByPath(String path) Texture
Get getSoundByPath(String path) Sound
Get getStageByName(String name) Stage
Get getMusicByPath(String path) Music
Add addStage(Stage stage, String name) boolean
Dispose disposeTexture(String internalPath) -
Dispose disposeTexture(String[] internalPaths) -
Dispose disposeSound(String internalPath) -
Dispose disposeSound(String[] internalPaths) -
Dispose disposeStage(String name) -
Dispose disposeStage(String[] names) -
Dispose disposeMusic(String internalPath) -
Dispose disposeMusic(String[] internalPaths) -
Dispose disposeAllResources() -

Data-structure

A note on the data-structure used. Currently, one arrayList of each resource managed is used. So for instance, there are 4 ArrayList used to store the resources.

An alternative would be to use hash-maps, but first off, arraylist are more efficient for the add operation, and secondly the amount of objects managed per type of resources is not quite big, the lists themselves remains small. This choice of design may be re-discussed in the future if the amount of resources managed grows a lot.

Why use it

The total control over managed resource lead to a reduction of loading times and less memory consumption, and eventually memory leak.

For example, let's take game 1. In a previous and old version, textures used by viruses were loaded each time a virus appeared. If the same virus appeared twice, the textures were also used twice. Of course this bad behaviour can easily be avoided by using a list in the class. The texture can be then disposed in the dispose method of the screen. Now with the use of the back button, the resources used would be lost after coming back. When the player want to play the game again, the resources are loaded again, the old ones staying in memory forever, until the garbage collector catch them.

Using a centralized unit like the Assetmanager is a solution to these problems. But to be efficient of course, the developers needs to use it everywhere. Not doing so may lead to memory leaks, or worse, app crashes.

Keep also in mind that textures are also reused thorough the game. Dispose the white background is a very bad idea of instance, as it is used in absolutely every screen. It should stay loaded in memory to avoid loading times.