[Solved] Unity 5.x freezes when running at the end of this lecture

When I ran the code from list lecture, it crashed Unity.

I think the iterator for children has changed from 4.x to 5.x and it is now updated with the complete list of children on every iteration which causes an infinite loop. I solved this by modifying the code to be:

    Transform[] children = GetComponentsInChildren<Transform>();
    foreach (Transform child in children)
    {
        GameObject enemy = Instantiate(EnemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
        enemy.transform.parent = this.transform;
    }

Can anyone confirm this is still correct and what changed between Unity 4.x and 5.x?

4 Likes

It is doing this for me too :frowning:

I realized my mistake now, the the code I typed incorrectly was:

enemy.transform.parent = transform;

it should have been:

enemy.transform.parent = child;

Small change makes a big difference! :slight_smile:

Any clue as to why enemy.transform.parent = transform caused an infinite loop?

I just tripped over this too - very annoying as it takes Unity out completely, losing unsaved changes.

Here’s why it loops infinitely:

Marking the new enemy as having the ‘Enemy Formation’ object as its parent means that the new enemy becomes a child of the ‘Enemy Formation’. (Yeah, so far so obvious.)

But we’re busy iterating over those children (which are supposed to be the Position objects). So we get to the end of the Position objects and now find a bunch of Enemies too. So we create enemies for each of those, which we then iterate over, and so on and so on. So it just keeps creating new enemies for each Position or enemy. If the foreach ignored non-Position objects, it’d be fine. It’s almost always a bad idea to iterate over something you’re changing. But here it’s not terribly obvious that setting a parent on another object changes the child array.

1 Like

Right, so basically it’s an exponential amount of instances that just completely knocks the program out. If you check the performance monitor you can actually see Unity eating up all the RAM gradually over time. I didn’t have the guts to wait until it chewed through my whole 8 gigs :smiley:

Privacy & Terms