Reputation: 1573
How does this work? I had trouble finding tutorials/documentation on using the same loaded image for many textures.
What I did at first was use something like Object obj("image.png");
, which wraps an SDL_Texture
in an Object. When calling Object's constructor, it loads "image.png" each time. Obviously, this is bad design if you want multiple sprites using the same image. It should only need to be loaded once.
So what I have now is a Sprite
class, which wraps an SDL_Texture
inside of it, like so:
struct Sprite {
SDL_Surface* sprite = NULL;
Sprite(const char* filename) {
sprite = IMG_Load(filename);
}
};
And I also have an Instance
class, which uses a Sprite
to create textures:
struct Instance {
Sprite* sprite = NULL;
SDL_Texture* texture = NULL;
Instance(Sprite* spr, WindowWrapper* wr) {
texture = SDL_CreateTextureFromSurface(wr->renderer, sprite->sprite);
SDL_FreeSurface(sprite->sprite);
}
}
So then what I do in main is load sprites into Sprite objects:
vector<Sprite*> sprites;
sprites.push_back(new Sprite("image1.png"));
sprites.push_back(new Sprite("image2.png"));
sprites.push_back(new Sprite("image3.png"));
...and then load these into Instance
objects.
Instance* i0 = new Instance(sprites[0], &theWindow);
Instance* i1 = new Instance(sprites[0], &theWindow);
But this kills the program.
It's not a problem with me rendering it, it doesn't even get to the rendering. It just kills the program when I call new Instace()
.
I suspect that you can't load the same SDL_Surface
into different SDL_Textures
. So then how do I make it so that I only have to load a certain sprite once and then I can use that same sprite over and over again for different textures?
Upvotes: 2
Views: 2529
Reputation: 8861
I think you need some more coffee :) Look at your Instance constructor. It frees the SDL_Surface. Of course you can't reuse it after that.
The SDL_FreeSurface call should be moved to Sprite's destructor. Then you'll be able to use a Sprite multiple times.
Upvotes: 2