SFML forum,
I'm using SFML but this might be a C++ OOP question.
I want to use a sprite from a class in all my objects:
class Sprite
{
public:
Sprite() {};
sf::Texture MySprite;
sf::Sprite sprite;
void Load_Sprite()
{
if(!MySprite.loadFromFile("C:/sprites/MySprite.png"))
{ cout << " Texture Loading Error" << endl; system("pause"); }
sprite.setTexture(MySprite);
}
};
But I have go use one of the objects to load the sprite so now it
belongs to that object. I would like to make the sprite static so
I only need one and use it in every object.
Any suggestions on how to do that?
Jerryd
Don't do that, just use one sprite per object. There's no problem in having many sprites, that's what they are for.
You should do that with your textures, though, because textures use more resources. Try to use only one texture for all your sprites, and to achieve that don't have a texture inside your class, but rather create your textures outside and just pass them to your "Load_Sprite()" method.
Something like this:
class Object {
public:
sf::Sprite mySprite;
void load_sprite( sf::Texture & externalTexture ) {
// It receives the texture externally as a parameter.
// Don't forget to use the "&" symbol, meaning that
// you are passing the texture "by reference".
// (If you don't know what this is,
// I strongly recommend reading about it).
mySprite.setTexture( externalTexture );
}
};
int main() {
// You load your textures externally, NOT inside your class.
sf::Texture myTexture;
myTexture.loadFromFile("image.png");
// You make instances of your class,
// and you pass your textures as necessary.
Object myObject;
myObject.load_sprite( myTexture );
Object anotherObject;
anotherObject.load_sprite( myTexture );
Object thirdObject;
thirdObject.load_sprite( myTexture );
...
}