SFML community forums

Help => General => Topic started by: Grime on August 15, 2019, 07:06:22 am

Title: How do I share a texture object amongst object instances?
Post by: Grime on August 15, 2019, 07:06:22 am
Here is an example class that I wrote:

class example {
private:
        sf::Texture player_texture;
public:
        sf::Sprite player_sprite;

        example() {
                player_texture.loadFromFile(fight_sprite_location);
                player_sprite.setTexture(player_texture);
        }
};

So the above class lets you make an object of the class and use that object's sprite instead of having to declare the texture and sprite in the main function.

Basically it's for tidying up my main function a  bit.

The problem however is that I might want to instantiate multiple instances of the class (all using the same texture itself, just their sprite attributions like position etc differ).

In that case each instance would have a separate texture object, which is a waste because really all the class instances need the same texture.


Is there a way to share a texture amongst object instances without having to allocate a new texture in each of the objects, and without having to declare a texture where the object has been created (I want as less code in main as possible, because I want my friends to be able to read the code).

Maybe something with the static keyword?

thx for reading  :)



Title: Re: How do I share a texture object amongst object instances?
Post by: eXpl0it3r on August 15, 2019, 09:26:34 am
The object could hold a reference to a texture which you pass in via constructor.
Then you can manage the texture outside of your entity objects with something like a resource holder (https://github.com/SFML/SFML-Game-Development-Book/tree/master/02_Resources/Include/Book).

That's just one way to approach it, but it's generally recommended to not store the texture as part of your game objects as it's a heavy resource and as you noticed, you often want to share the same texture among multiple objects.