While Loop Freezing Unity
What's wrong with this code? Whenever OnMouseDown is called unity freezes.
public class createTroops : MonoBehaviour {
public stats statsVars;
public GameObject prefab;
public int incPos = 4;
void OnMouseDown()
{
while (statsVars.units <= statsVars.units + statsVars.units)
{
Instantiate(prefab, new Vector3(-23.3f, 10 - incPos, 0), Quaternion.identity);
statsVars.units++;
}
if (statsVars.units >= statsVars.units + statsVars.units)
{
statsVars.units = 0;
}
}
}
Answer by MaxGuernseyIII · Aug 30, 2017 at 06:44 AM
The condition of your while loop is that a number is less than or equal to twice itself, which is true for every non-negative number. This causes your loop to run forever. Since it's doing it in the main thread, that causes Unity to appear to freeze.
I feel like what you maybe want to do is create statsVars.units prefabs? If so, make a separate counter variable to be incremented and tested against the upper boundary. That will let you break out of the loop.
I'm so dumb, thank you. but wait, since it increases every time the loop runs, shouldn't that break it?
Both sides of the condition (statsVars.units
"statsVars.units" will forever be smaller than 2x "statsVars.units".
One of the reasons we collaborate is that sometimes you just need a fresh set of eyes on something. :)
Your answer
Follow this Question
Related Questions
[Solved]Cant Find loop that freezes Unity 2 Answers
Why does this while loop freeze unity? 1 Answer
While Loop not working when clicked on Play button 1 Answer
While loop freeze 0 Answers