- Home /
For loop never exits
This section of code inside of a for loop with "print("here")" after it fails. It never reaches/ prints "here". I know I am probably missing something simple but I am tired of looking at it. Help.
GameObject[] halls = GameObject.FindGameObjectsWithTag("hallway");
PolygonCollider2D[] colliders = new PolygonCollider2D[halls.Length - 1];
int cornerNum = 0;
float shortestDist = Mathf.Infinity;
Vector2 closestCorner = new Vector2(100, 100); //efectively null (useless)
GameObject closestHall = null;
for (int i = 0; i <= halls.Length; i++)
{
if (halls[i] == gameObject) return;
colliders[i] = halls[i].GetComponent<PolygonCollider2D>();
if (halls[i].layer == 8)
{
cornerNum += 4;
}
else if (halls[i].layer == 9)
{
cornerNum += 6;
}
else if (halls[i].layer == 10)
{
cornerNum += 12;
}
}
print("here");
Answer by Bunny83 · Sep 19, 2019 at 01:34 AM
I don't see any reason that this for loop might cause an infinite loop (aka never exits the for loop). An actual infinite loop would actually cause a hang and would cause the Unity editor or your build game to not respond anymore. If that does not happen (which is most likely the case) your for loop does exit.
Since you have an explicit return statement in your for loop, that's most likely causing the method to terminate. Keep in mind that a return statement does not exit the for loop and continue execution after the for loop. The return statement belongs to the method that is executing and will exit the method on the spot
So if your condition is true:
if (halls[i] == gameObject) return;
your method will terminate without ever reaching that print statement at the end.
Yes, the return is likely meant to be a continue statement ins$$anonymous$$d.
Although if it wasn't there they would be getting an Index Out Of Range Exception as it should be i < halls.Length not
Thank you, that was the problem. I thought return only did the most local method/ loop.