Hello,
I'm doing a simple GameEngine and currently i'm working on the SpriteManager.
So i've a function addSprite(const std::string file) wich will load a texture and create a sprite that will be added to a spriteCollection (and then the game objects will have an index wich referes to that sprite). But i've a Bad Acess Memory. My vector is empty. What did I missed ?
int SpriteManager::addSprite(const std::string file)
{
sf::Texture* tmpTexture = new sf::Texture;
if(tmpTexture->loadFromFile(file)){
spriteCollection.push_back(new sf::Sprite);
spriteCollection[spriteCollection.size() - 1]->setTexture(*tmpTexture);
}else{
return -1;
}
return spriteCollection.size() - 1;
}
sf::Sprite* SpriteManager::getSprite(int index)
{
return spriteCollection[index]; //There is a BAD ACCESS (of course beacause spriteCollection is empty)
}
Thank in advance
You should use RAII instead of manually managing your memory, see Nexus' awesome article (http://bromeon.ch/articles/raii.html).
That being said, you most likely want to store the textures rather than the sprites. Sprites are usually bound to entities and thus I'm not sure what a SpriteManager would really do.
Also, this:
spriteCollection[spriteCollection.size() - 1]->setTexture(*tmpTexture);
Could be written way safer and more expressive like this:
spriteCollection.back()->setTexture(*tmpTexture);
You might want to add an asser to the getSprite function and make the index of an unsigned type:
assert(spriteCollection.getSize() > index);
That way, if the index is out of bound (since unsigned it can only be positive), it would fail in your own assert.