I remember reading somewhere that it's best to instantiate a Texture once and then pass it in the constructor of the object you want to use. So for the longest time that's what I've been doing. The problem arises when I see my code become more and more clunky because of the large amounts of textures I load once in a single area. So should I just create a new texture with every object, or just have a separate class of which you can obtain the textures? Thank you! ;D
I would suggest having a TextureFinder class where you do something along the lines of
TextureFinder.lookFor("filename.png");
which could also load the textures if not loaded already.
If you have one texture that’s re-used for many objects, DO NOT load them over and over and over… because you’ll have to dispose of them later!
Libgdx’s AssetManager is a great way to load the textures at runtime. You can call the update method to load them in your loading screen. When you want to get a loaded asset, you can call
manager.get("filepathhere", Texture.class)
The only downside to this is you’ll have to remember the entire filepath, so what I did was make a singleton class that stored a list of keys and values. You could reference a filepath by a nickname you gave it. Some code I have from a project is here. AssetManager also has a handy dispose method that disposes everything it has loaded.
I don’t know if this is a great option, but I often declare textures in a class to control all the assets. All the textures are loaded with the game and are static type, so I can reuse all of them just using AssetsController.texture_name.
I can create N sprites/others using only one instance of texture.
While that probably works fine and is easy to implement, it can potentially give you a lot of headaches in Android with the loss of context when the user exits and re-enters the app, unless you reload all of the textures in Onresume (which is acceptable if the game is small).
Have something like an asset manager that has stored all textures in a hashmap or a list and you can do AssetManager.getTexture(“somettexture.png”); which would return a texture.
Thank you all for you help! I ended up using craftm’s method of doing this, and while I was at it I also added a progress bar so I call this a success!
Also think about using a
TextureAtlas
(if you don’t do this already). It can reduce the Texture bindings and therefore increase performance.
If you have many Textures, you may want to “group” them into different atlases and load every atlas only when needed. For example one for the main menu, loaded on startup and one for the game, loaded only, when you actually start playing.
Use the AssetManager supplied with the LibGDX library. Load textures once, use Sprites with them for multiple draw transforms.
Do not put the textures into a class and declare them all static, this is a bad habit and you will suffer from OpenGL context lost on the Android platform.