Search code examples
c++imagevectortexturessfml

Failed to load image to texture vector (SFML)


We are trying to load textures to a vector of textures in order to be able building a game. The program is thrown once getting to the line where we are trying to load the image to the vector. The vector's definition is:

vector> m_textureVec;

#include "Resources.h"
#include <thread>
#include <SFML/Graphics.hpp>

using std::vector;

Resources Resources::m_instance = Resources();

Resources::Resources()
{
    vector<unique_ptr<sf::Texture>> m_textureVec;
    m_textureVec.resize(8);

    m_textureVec[0]->loadFromFile("digger.png");
    m_textureVec[1]->loadFromFile("monster.png");
    m_textureVec[2]->loadFromFile("diamond.png");
    m_textureVec[3]->loadFromFile("present.png");
    m_textureVec[4]->loadFromFile("stone.png");
    m_textureVec[5]->loadFromFile("wall.png");
    m_textureVec[6]->loadFromFile("background.png");
    m_textureVec[7]->loadFromFile("empty.png");
}

Solution

  • You need to allocate memory for the unique_ptr to hold. Right now you have 8 unique_ptrs with nothing to point to.

    Resources::Resources()
    {
        vector<unique_ptr<sf::Texture>> m_textureVec;
        m_textureVec.resize(8);
    
        m_textureVec.push_back(std::unique_ptr<sf::Texture>(new sf::Texture()));
        m_textureVec[0]->loadFromFile("digger.png");
        //etc
    }
    

    Also, you will lose your m_textureVec when your Resources() function finishes. It's best to create that variable in a more long-lasting environment.