- Home /
While Loop within For Loop crashes Game
Hello! I want my Token spawn algorithm to not spawn more than 2 of the same type in a row. therefore i'm using a while loop within a for loop to check if the same color is within the spawn list more than 2 times.
I tried out several things but i can't see why this would produce an infinite loop:
for (int i=0; i<_tokenList.Length; i++)
{
while (!canAddToken) {
tokenToAdd = _tokenType[Random.Range(0,maxTokens)];
createdTokenList.Add(tokenToAdd);
lastTokenAmount = 0;
foreach (string tokenToCheck in createdTokenList)
{
if (tokenToCheck == tokenToAdd)
{
lastTokenAmount += 1;
}
}
if(lastTokenAmount > 2)
{
createdTokenList.Remove(tokenToAdd);
canAddToken = false;
}
else
{
canAddToken = true;
}
}
_tokenList[i] = tokenToAdd;
canAddToken = false;
}
Add in some strategic Debug.Log( variable ) calls to see if its doing as you expect.
Is your goal not to have two of the same type of thing in _tokenList in a row? Cause what you are doing wouldn't solve that. Also, I find it strange that you add tokenToAdd to createdTokenList THEN you look through and compare everything in createdTokenList to tokenToAdd.. you are guaranteed 1 hit every time. It's weird.
The goal would be to avoid more than 2 in a row. 1,1,2,2,3,1,2 would be ok, 1,1,1,2,3,2,1 would be not ok
A while loop can run for an indefinite amount of time. Doing this for each iteration of a for loop is very likely to grind your game to a halt unless your while loop logic is infallible.
Well you aren't checking for two in a row are you? You are checking all of them - therefore if the list is long enough it will quickly get to a situation where you have two of every token and then will loop infinitely.
Answer by whydoidoit · Oct 22, 2013 at 07:24 PM
for (int i=0; i<_tokenList.Length; i++)
{
while (!canAddToken) {
tokenToAdd = _tokenType[Random.Range(0,maxTokens)];
canAddToken = i<2 || !(tokenList[i-1] == tokenToAdd && tokenList[i-2] == tokenToAdd);
}
_tokenList[i] = tokenToAdd;
canAddToken = false;
}
Without the loop:
for (int i=0; i<_tokenList.Length; i++)
{
var tokenIndex = Random.Range(0,maxTokens);
tokenToAdd = _tokenType[tokenIndex];
_tokenList[i] = i<2 || !(tokenList[i-1] == tokenToAdd && tokenList[i-2] == tokenToAdd) ? tokenToAdd : _tokenType[(tokenIndex + 1) % _tokenType.Length];
}
thanks for the rather impressive answer, but the console says: Operator ==' cannot be applied to operands of type
bool' and `string'
the content of my _tokenList are actually strings.
i'm using c# btw
(tokenList[i-1] == tokenList[i-2] == tokenToAdd)
Yeah that won't work.