'Code causes infinite loop in start function of Unity
I was wondering how I would avoid an infinite loop by running this code within the start function in unity.
void Start ()
{
Room[] rooms = generateRooms();
int falseCount = 0;
while (true)
{
for (int i = 0; i < rooms.Length; i++)
{
if (!rooms[i].separationFlocking(rooms)) {
falseCount++;
}
}
if (falseCount >= rooms.Length) break;
}
}
separationFlocking returns false if the object didn't need to be moved, so if rooms.Length number of objects weren't moved then I want it to break the while loop. Although, everytime I compile it, it never seems to compile to play mode, presumably because of the infinite loop.
void Update ()
{
int falseCount = 0;
if (falseCount != rooms.Length) {
for (int i = 0; i < rooms.Length; i++)
{
if (!rooms[i].separationFlocking(rooms)) {
falseCount += 1;
}
}
}
}
If I run similar code in the update function it seems to work fine, so I know that detecting if the object didn't move isn't broken.
When I run the start function with a iterator that breaks after 100 loops I get this result. The cubes seem to separate from each other in odd ways, spreading out from their original circular arrangement.
This is how they're supposed to turn out and they successful do so in the update function. Although, I want to avoid running this code every frame for performance reasons.
This whole project is based on this blog post. Also here's the pastebin link so you can see the whole code. If you want to run it in unity all you need to do is add it to an empty game object.
Solution 1:[1]
You need to call the method continously? I would call it only when needed. If you one to lower the call frequency you can space that call in the update, or use a corroutine. Not debugged examples below.
frequency execution control in the update:
float elapsedTime = 0f;
int runFreqTime = 2; //to run every 2 seconds
void Update ()
{
elapsedTime += Time.deltaTime;
if (elapsedTime > runFreqTime) {
int falseCount = 0;
if (falseCount != rooms.Length) {
for (int i = 0; i < rooms.Length; i++)
{
if (!rooms[i].separationFlocking(rooms)) {
falseCount += 1;
}
}
}
elapsedTime = 0f; //time control float reset
}
}
coroutine:
public void Start() {
StartCoroutine(RepetitiveExec());
}
IEnumerator RepetitiveExec()
{
while (true)
{
for (int i = 0; i < rooms.Length; i++)
{
if (!rooms[i].separationFlocking(rooms)) {
falseCount++;
}
}
if (falseCount >= rooms.Length) break;
}
yield return new WaitForSeconds(2f);
}
Need to be careful with coroutines. It would be executing until you Stop it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


