Hi all,
I had a
working project that was about 4000 lines of code, already using many
sf::Texture and
sf::Text objects. Then I decided that I need a texture manager to optimize loading many files. Here is the code:
//Declarations
class Manager
{
private:
static map<string, Texture > textures;
public:
static Texture & add(const string & name, const string & directory);
static Texture & resolve(const string & name);
};
//Definitions
Texture & Manager::add(const string & name, const string & directory)
{
// Check, whether a said texture was already maped
map<string, Texture>::const_iterator it = textures.find(name);
if (it != textures.end())
{
cout << "Said element was loaded" << endl;
return textures.at(name);
}
// Adding a new texture
Texture tex;
tex.loadFromFile(directory);
textures[name] = tex;
cout << "Texture added" << endl;
return textures.at(name);
}
Texture & Manager::resolve(const string & name)
{
cout << "Resolved" << endl;
return textures.at(name);
}
map<string, Texture > Manager::textures;
And I wanted to test it so I replaced this:
void Engine::set_up(int & lvl)
{
Texture texture;
texture.loadFromFile("data/loading_screen.png");
Sprite spr;
spr.setTexture(texture);
// ...
}
with this:
void Engine::set_up(int & lvl)
{
srm::Manager::add("Loading screen", "data/loading_screen.png");
Sprite spr;
spr.setTexture(srm::Manager::resolve("Loading screen"));
// ...
}
What happened: this is the loading screen. So I pressed "PLAY". Everythink worked, the loading screen appeard, level has been loaded. I got back to main menu and pressed "PLAY" again. And now, for some reason, I get Runtime Library Error:
http://ifotos.pl/z/sexsqph. I tought it is caused by new code. But when I tried to debug, it turned out that my game stops on setting
sf::Text objects. Random one, to be precised, in random method, some times in the
Engine::set_up() method, sometime in other methods. And I am confused. It looks that these are colliding.
What's more, when I moved
srm::Manager::add() calling to the constructor of Engine class, everything works fine again
(it looks like this):
//Constructor
Engine(){ srm::Manager::add("Loading screen", "data/loading_screen.png"); }
//Method
void Engine::set_up(int & lvl)
{
Sprite spr;
spr.setTexture(srm::Manager::resolve("Loading screen"));
// ...
}
So can you explain me, whats going on in my project? I don't understand why it's behaving like this? How can I improve my code to make it working perfectly? Thank you in advance!