here's some code for a simple resourceHolder that im using atm, largely based off one that's in the book sfml essentials, main difference between them is that in the book they make the class a singleton. In this case i dont bother, because im lazy and i know that only my game class should hold the resourceHolder, other classes that need a texture get handed a pointer to it. Anyways, here's some code:
header:
class resourceHolder
{
public:
resourceHolder();
sf::Texture& getTexture(std::string path);
sf::Font& getFont(std::string path);
sf::SoundBuffer& getSound(std::string path);
private:
std::map<std::string, sf::Texture> textures;
std::map<std::string, sf::Font> fonts;
std::map<std::string, sf::SoundBuffer> sounds;
};
cpp file:
#include "resourceHolder.h"
resourceHolder::resourceHolder()
: textures()
{
}
sf::Texture & resourceHolder::getTexture(std::string path)
{
auto& pairFound = textures.find(path);
if (pairFound != textures.end()) {
return pairFound->second;
}
else
{
auto& texture = textures[path];
texture.loadFromFile(path);
return texture;
}
}
sf::Font & resourceHolder::getFont(std::string path)
{
auto& pairFound = fonts.find(path);
if (pairFound != fonts.end()) {
return pairFound->second;
}
else
{
auto& font = fonts[path];
font.loadFromFile(path);
return font;
}
}
sf::SoundBuffer & resourceHolder::getSound(std::string path)
{
auto pairFound = sounds.find(path);
if (pairFound != sounds.end())
{
return pairFound->second;
}
else
{
auto& sBuffer = sounds[path];
sBuffer.loadFromFile(path);
return sBuffer;
}
}
basically, you just use this class to store your textures sounds whatever, and they stay there without being destroyed until the program exits. For each type of resource there is a map object that stores the resources filepath as its id and a resource of the desired type. It checks the map to see if that resource already exists - if it does, it returns it, if it doesn't, it adds it then returns it. To simplify the file paths, I wrote them as const strings in a header file behind a namespace and include that in the project too. So for example, instead of writing "graphics/player.png" i can instead type something like Sprites::player.
Hope this helps and isn't too awful a way of doing it.