keep order of textures in for-loop?

Hey guys,

currently I’m wondering why my loop is not working as expected. I’m using yield to wait for the texture to load before getting the next one, but it doesn’t seem to work correctly sometimes.

for(int i=0; i<statics.userID.Length; i++)
{
	if(statics.userID[i] != "")
	{			
		WWW iconRequest = new WWW(myURL + statics.userID[i] + "/picture");
		yield return iconRequest;						// wait till we received the image
				
		statics.userIcon[i] = iconRequest.texture;		// set image when found
			
		if(statics.userIcon[i] == null)					// we couldn't find an image, use template
			statics.userIcon[i] = statics.noUserIcon;	// assign template image
	}
	else
	{
		statics.userIcon[i] = statics.noUserIcon;		// we do not have an ID so no picture request is needed
	}
}

This is within a “IEnumerator GetImage() { }” function and gets called with StartCoroutine(GetImage());

But sometimes the images are flipped, like User2 and User3 are on the right position (on leaderboard by level) but their images are changed, so User2 has the image of User3 and the other way round. Mostly this worked ok with different levels, but it’s failing a lot if both have the same level…

I thought when I use yield it waits for the image, sets it to it’s correct variable and then runs the next loop, am I wrong with this?

Thanks in advance :slight_smile:

If i am not mistaken yield does not stop your increment from incrementing with the loop

if the problem is with the loop itself those two things should help you fix it

However if the problem is that img2 and img3 are swapping places its hard for an increment to count down with that code so i think it is much more likely you have a logical error when you are setting up static’s data structure

Problem solved! But it’s a bit different, so I guess we have to clear some things out to prevent mistakes.

  1. I think the “yield return iconRequest;” works pretty fine with www, also within for-loops. I guess the yield works on all (or at least the most) parts within a Coroutine. So the images I tried to get were always on the same position with every reload-try I did, so I assume it works as it should.

  2. I was sorting the list when I received more information from my database. So the order of List1 and List2 (in this case) wasn’t the same. I was trying to get the images from List1 while I got the names from List2. That’s why I was confused about the images that were on the wrong names, but I didn’t thought/remebered the part with the database-sorting stuff ^^

I used the correct list now, and everything works fine as it should, also on several reload trys to check for errors or mistakes that could happen, but everything still works. Thanks for the help and links KaBKa, though! :slight_smile:

(can be closed)