Search code examples
c++visual-c++sfml

How do I fix this textureBackground identifier in Visual Studio 2017 using C++


I've experienced a problem when trying to declare an identifier. The main part is textureBackground.loadFromFile("graphics/background.png"); where textureBackground is the one being underlined

I've tried adding parentheses, changing uppercases, lower cases, check file locations, etc.

int main()
{
    //Create a video mode object
    VideoMode vm(1920, 1080);

    // Create and open a window for game
    RenderWindow window(vm, "Scarful!!!", Style::Fullscreen);
    while (window.isOpen())

        // Texture for graphic on cpu
        Texture textureBackground;

        // Load graphic into texture
         textureBackground.loadFromFile("graphics/background.png");

        // Make Sprite
        Sprite spriteBackground;

        // Attach texture to sprite
        spriteBackground.setTexture(textureBackground);

        // Set spritebackground to cover screen
        spriteBackground.setPosition(0, 0);
    {
        /* Handle player input */

        if (Keyboard::isKeyPressed(Keyboard::Escape))
        {
            window.close();

        }

        //Update Scene


        //Draw Scene
        window.clear();
        //Draw Game Scene
        window.draw(spriteBackground);

        //Show everything we drew
        window.display();
    }
    return 0;
}


Solution

  • Here,

    while (window.isOpen())
        // Texture for graphic on cpu
        Texture textureBackground;
    // Load graphic into texture
    textureBackground.loadFromFile("graphics/background.png");
    

    You are trying to do this:

    while (window.isOpen()) {
        // Variable goes out of scope outside of the loop...
        Texture textureBackground;
    }
       textureBackground.loadFromFile("graphics/background.png");
    // ^^^^^^^^^^^^^^^^^ is not available anymore...
    

    And since textureBackground is out-of-scope you cannot modify it anymore... I suggest you wanted...

    // Texture for graphic on cpu
    Texture textureBackground;
    
    // Load graphic into texture
    textureBackground.loadFromFile("graphics/background.png");
    
    // Make Sprite
    Sprite spriteBackground;
    
    // Attach texture to sprite
    spriteBackground.setTexture(textureBackground);
    
    // Set spritebackground to cover screen
    spriteBackground.setPosition(0, 0);
    
    while (window.isOpen()) {
        // Other code goes here...
    }