Kavi
Kavi

Reputation: 113

LibGdx One or Multiple instances for several objects

I'm going through tutorials to learn Libgdx and every time I see, use same instances or variable to output your sprite objects. So, I can understand that if we want to create and render the same image or sprite, we can simply use the same variables. But now, I need to display several objects (different players/images). Can I still use the same variables to output them or should I create variables for each of them? Cause I've seen it saves space and memory. To output sprites I'm using SpriteBatch, Texture, Sprite and TextureRegion(for moving sprites) objects.

Upvotes: 0

Views: 902

Answers (1)

Sneh
Sneh

Reputation: 3747

No you cannot use same sprite object for different entities (Players etc) This is not where you will be saving memory. Creation of Sprite object is not heavy weight operation.

Where you can save memory is Textures. You should reuse Textures wherever possible. You do not want to load new Textures every time you create a new Sprite. Let's say there is 1 image which represents a player, you should not be creating that image again and again. You should rather just load it once in memory using AssetLoader and then re-use it.

If you have multiple texture of small sizes, then you should use libgdx's texture packer to pack them into a single image because loading multiple small textures is not a great idea, rather loading a bigger texture sheet is fine because binding Textures is an expensive operation. Read this Texture Atlas for more detailed information.

Also once you don't need a Texture, you should dispose them.

Read this page Memory Management in Libgdx for more information about Disposable interface which is implemented by many of the Libgdx classes.

I also feel that you are trying to optimise your game prematurely. Don't worry about object creations at all at such an early stage. And remember one more thing - Premature optimization is the root of all evil.

Upvotes: 2

Related Questions