I'm using SFML, and my game is coming along well. After implementing a player and tile system, I decided to make enemies. My enemies are stored in a std::vector, and they use a copy constructer that defines their position in the game. I've been trying for hours on end to get their textures to load correctly, but they don't. My player and tiles' textures load fine, but the enemies' textures will either display nothing or a white box depending on what I do. I pushed back an instance in main for testing, and I either get a white box, nothing, or the texture of a different object. I made sure the file path is correct and everything, but the texture just doesn't show correctly. Here is skeleton.h:
#include "Common.h"
class Skeleton {
public:
Skeleton(RenderWindow* window, vector<Skeleton> *skeletonVector);
Skeleton(float& x, float& y);
void draw();
void update();
Sprite sprite;
private:
Texture texture;
RenderWindow* window = nullptr;
vector<Skeleton>* skeletonVector = nullptr;
const float SPRITE_SIZE;
};
and here is skeleton.cpp:
Skeleton::Skeleton(RenderWindow* window, vector<Skeleton>* skeletonVector)
:SPRITE_SIZE(16.f)
{
texture.loadFromFile("Skeleton/s.png");
this->window = window;
this->skeletonVector = skeletonVector;
}
Skeleton::Skeleton(float& x, float& y)
:SPRITE_SIZE(16.f)
{
this->sprite.setTexture(texture);
this->sprite.setOrigin(SPRITE_SIZE / 2, 0.f);
this->sprite.setPosition(x, y);
}
void Skeleton::draw(){
for (int i = 0; i < skeletonVector->size(); i++) {
window->draw(skeletonVector->at(i).sprite);
}
}
void Skeleton::update()
{
}
I already called draw in main, created an instance with the first constuctor to take in the window and vector from main, and pushed back an instance of my object in the vector. Could someone please try to explain why the textures aren't showing correctly? I'm open to any critisism or code changes too. Thanks!
this->skeletonVector = skeletonVector;just copies a pointer, not any data. If the original is destroyed, perhaps by going out of scope, then you have a dangling pointer. Since you didn't show us how this code is used it's hard to say what the issue is. It's also worth noting that the other constructor leaves the vector pointer set tonullptrand callingdrawwith an object like that is undefined behavior and very likely a crash.windowandskeletonVectorwill remain set tonullptr.