-1

I made a small project in C++ using SFML. I added sprites (a character). I have organized the sprites like Assets/Player/Idle/Idle1.jpg then Idle2.jpg and so on.

I initialize the sprites like this:

texture = new Texture[116];
sprite = new Sprite[116];
texture[0].loadFromFile("Assests/Iori/Ready1.png");
sprite[0].setTexture(texture[0]);
texture[1].loadFromFile("Assests/Iori/Ready2.png");
sprite[1].setTexture(texture[1]);
texture[2].loadFromFile("Assests/Iori/Ready3.png");
sprite[2].setTexture(texture[2]);
texture[3].loadFromFile("Assests/Iori/Ready4.png");
sprite[3].setTexture(texture[3]);
texture[4].loadFromFile("Assests/Iori/Ready5.png");
sprite[4].setTexture(texture[4]);
texture[5].loadFromFile("Assests/Iori/Ready6.png");
sprite[5].setTexture(texture[5]);
texture[6].loadFromFile("Assests/Iori/Ready7.png");

And so on. Now this method works fine and loads my sprites completely. But I don't think this is the efficient or right method. I have to load up 100+ sprites and that would just be a mess for a programmer.

I was wondering can you initialize these sprites via a loop (for/while) that would reduce the code a lot.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Hassan Yousuf
  • 751
  • 6
  • 12
  • 24
  • 3
    Well, you should definitely use a loop. But what is the question? – awesoon Dec 28 '15 at 18:42
  • @soon How do I initialize them with loops? – Hassan Yousuf Dec 28 '15 at 18:42
  • You should generate a path to file on each iteration and pass it to the `loadFromFile` function. – awesoon Dec 28 '15 at 18:43
  • @soon But how will it iterate through the next picture? Can you please show me a code snippet if you don't mind? – Hassan Yousuf Dec 28 '15 at 18:45
  • I suggest you pick up a [good book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and work through all provided exercises. `for` and `while` loops are basic constructs in high level languages. – Captain Obvlious Dec 28 '15 at 18:54
  • 1
    Yes, this should be a loop. As you seem to have problems, what *can* you do? Can you write a loop counting from 0 to 100? Can you manipulate a string so a certain placeholder is replaced by the loop counter? Can you use the loop counter as your array index? Post your best try and people will help you. Right now, we are reluctant, because all you did was ask for code and that's not how this site works. If you show effort, you will get help. – nvoigt Dec 28 '15 at 18:54

1 Answers1

2

Use basic for loop and construct name of the texture dynamicaly.
You might need to use explicit cast to std::string or char* depending on the loadFromFile method.

static const int count = 116;
texture = new Texture[count];
sprite = new Sprite[count];

for (int i = 0; i < count; ++i)
{
    texture[i].loadFromFile("Assests/Iori/Ready" + std::to_string(i + 1) + ".png");
    sprite[i].setTexture(texture[i]);
}
Zereges
  • 5,139
  • 1
  • 25
  • 49