Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How do I share a texture object amongst object instances?  (Read 1266 times)

0 Members and 1 Guest are viewing this topic.

Grime

  • Newbie
  • *
  • Posts: 13
    • View Profile
How do I share a texture object amongst object instances?
« 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  :)




eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
Re: How do I share a texture object amongst object instances?
« Reply #1 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.

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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything