Level genration loop crashing unity3D

I have an editor script that generates a random level, I have a for loop that checks for duplicates of certain objects and is supposed to reset and check if it finds one but it keeps crashing and freezing unity. What is wrong with my loop?

private int CheckForMultiple(int testBuilding, int roomIndex)
{
    int newBuilding = testBuilding;
    for(int i = 1; i < roomIndex; i++)
    {
        if(_indexes *== newBuilding)*

{
newBuilding = (int)Random.Range(0, backgroundElements.Count);
i = 1;//reset loop and start over
}
}
return newBuilding;
}

This is extremely dangerous and extremely inefficient code. It’s pretty obvious why the loop causes a hang (not a crash btw.). From your code it’s hard to tell what this method actually should do. Though if it hangs it means you send it into an infinite loop. That means your for loop will never exit. That means you always enter your if statement at some iteration of your for loop. This also means that you probably have just as many elements in your “_indexes” array / list as you have elements in your “backgroundElements” List. So each index from 0 up to backgroundElements.Count is already used at some of the “_indexes” elements. So no matter which random number you roll it will always appear in the “_indexes” and therefore you restart the loop endlessly.

Another point which is confusing is that you start your loop at index 1 instead of 0 which makes this code even stranger. Since we don’t have the full picture (we don’t know what “_indexes” actually is, what values it contains, how they are filled, how many elements it has and how many elements are inside backgroundElements).

If you want to avoid picking the same background element twice you should use a “bucket list” where you keep either the remaining / unused indices or the background objects itself. Each time you pick / use one you would remove that index / object from the bucket so you ever have only unused objects in your bucket. So you can safely pick a random index / object from the bucket. Also you immediately see when the bucket is empty and no unused elements are left so you either have to create an error at this point or return some default value depending on what exact behaviour you need.

Ughhhh… I finally fixed it after several hours. I found unity’s log file in the AppData folder and found my issue. So I switched to a while loop to make things a little easier and found I wasn’t updating one of my variables after assigning a new variable causing the while loop and for loop to both stick into an infinite loop and thus crash unity. With out that log file I doubt I would of fixed this.