How to best break out of this while loop?

I’m trying to write a random level picker, the idea is to never have the same level twice until you’ve had all of them. The levels are Game Objects that I’ve stored in a list. This is the code:

		bool unique = false;
		if (usedLevels.Count > 0) {
			while (!unique) {
				levelID = Random.Range (0, levels.Count);
				for (int i = 0; i < usedLevels.Count; i++) {
					if (i == usedLevels*) {*

_ if (usedLevels == levelID) {_
* unique = false;*
* break;*
* }*
* else {*
* unique = true;*
* }*
* }*
* }*
* }*
* }*

* Instantiate (levels[levelID]);*
* usedLevels.Add (levelID);*
* if (usedLevels.Count >= levels.Count)*
* usedLevels = new List ();*
This works for one round of levels but every time I get to the second level of the second round of levels Unity freezes. Which probably means it get’s stuck in the while loop, right? From making the usedLevels list public it seems to be reseting allright.
So how would I stop this from happening?

1 Answer

1

This is an unefficient and dangerous approach. It’s better to do it the other way round:

if (availableLevels.Count == 0)
    for(int i = 0; i < levels.Count; i++)
        availableLevels.Add(i);

int index = Random.Range (0, availableLevels.Count);
levelID = availableLevels[index];
availableLevels.RemoveAt(index);
Instantiate(levels[levelID]);

ps: this line is probably the reason for your crash: if (i == usedLevels*) {* It doesn't make any sense. usedLevels store level indices (into the levels array / List) while "i" is the index into the usedLevels List. This check will totally mess up your loops.

Thanks, that is way more efficient indeed!