0

I am trying to load 6 images into a std::vector(sf::Sprite) into my state machine. The state machine is working fine so I doubt that it is the issue.

I have a .txt file that contains the images' file names as

1.png
2.png
3.png
4.png
5.png
6.png

The images themselves are in the img/ directory.

Here is the relevant code:

std::ifstream file("images.txt");

while (!(file.eof()))
{
    getline(file, TmpString);
    filename.push_back(TmpString);
}

TmpString is just a string variable to store a single image's file name. filename is a vector of strings and using breakpoints, I can see that it has the correct strings (aka correct file names).

In the next loop, I use loadFromFile() to load the image into a sf::Texture called tempTex. I set the texture of a sf::Spritecalled tempSprite and add it to spriteList which is the std::vector<sf::Sprite>.

for (size_t i = 0; i < filename.size(); i++)
{
    tempTex.loadFromFile("img/" + filename[i]);
    tempSprite.setTexture(tempTex, true);
    spriteList.push_back(tempSprite);
}

The issue is, that whenever I draw any sprite from the spriteList to the window, its always the 6.png image. That is:

m_window.draw(spriteList[index]) always draws 6.png no matter what the index is.

ArmenHeat
  • 111
  • 8
  • 1
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Mar 28 '18 at 17:57
  • @NeilButterworth Changing the while loop to `while(file >> TmpString)` and then adding to the vector of strings does nothing. Like I said in my question, I have checked thru debugging that the vector of strings contains correct file names, the while loop is not the issue. The issue is somewhere in the for loop but I can't debug to see which image is in each index. The spriteList only contains the `6.png` image on all indexes. – ArmenHeat Mar 28 '18 at 18:22

1 Answers1

1

The SFML Sprites and Textures tutorial says

When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer.

Which from my understanding also means if you load a new texture into the same object, it is overwritten. The sprite will still be pointing to the same texture which has now changed. You'll need to keep a collection of textures.

kmdreko
  • 14,683
  • 3
  • 21
  • 41
  • Yes, this seems to be the issue, I tried making an array of `sf::Texture` where each index is assigned its own texture via `.loadFromFile()` and then set each sprite in an array of `sf::Sprite` to each index of the texture array. This didn't work either, which confuses me since the texture array isn't manipulated at all after it is initialized. I ended up making six `sf::Texture` objects and doing it that way, I'm sure it's not technically the right way... – ArmenHeat Mar 28 '18 at 22:50