Replies To: Looping through a vector.

Re: Looping through a vector.

Posted 20 June 2012 - 12:27 PM

Quote

So i am having trouble looping through a vector and drawing everything in it to the screen (using SFML).

Please tell us what KIND of trouble you are having? Help us understand what is happening, is it a syntax thing? Does it compile but does not draw the sprites? That is a lot of code to go swimming though looking for "trouble".

One thing I did note though -- you have two "enemyList" vectors -- one is a global variable (generally we try to avoid global variables) the other is a member of Game.

Re: Looping through a vector.

Posted 20 June 2012 - 01:19 PM

NickDMax, on 20 June 2012 - 08:27 PM, said:

Quote

So i am having trouble looping through a vector and drawing everything in it to the screen (using SFML).

Please tell us what KIND of trouble you are having? Help us understand what is happening, is it a syntax thing? Does it compile but does not draw the sprites? That is a lot of code to go swimming though looking for "trouble".

One thing I did note though -- you have two "enemyList" vectors -- one is a global variable (generally we try to avoid global variables) the other is a member of Game.

Make sure you know which one is which when you use it!

I didn't realise that made i global, i was just doing what i would in c#. The problem i was having when it wasn't global was that the vector would be destroyed after the addEnemy function was called.

If i keep the one that belongs to game in, i get a vector subscript out of range. If i leave it as a global it is now seeming to work. So i guess my problem is now how do i get the list from destructing itself after being used in addEnemy?

Re: Looping through a vector.

It is important to note that the sf::Sprite instance doesn't copy the texture that it uses, it only keeps a reference to it. Thus, a sf::Texture must not be destroyed while it is used by a sf::Sprite (i.e. never write a function that uses a local sf::Texture instance for creating a sprite).

You see enemyList.push_back(enemyTemp); makes a COPY of the sf::sprite which DOES NOT make a copy of the Texture, which means as soon as the Texture is out of scope it is destroyed.

So is the code that I got to "work" -- I don't think it is organized the best but that is something you will have to work out. Personally I think you will probably need to create and Enemy class to encapsulate the sprite and to ensure that the Texture remains intact when the object is copied (STL vectors do a lot of copying).