Question by 
               theleonn · Jan 07, 2017 at 02:00 PM · 
                bugforeachcomputer-crash  
              
 
              Foreach freezing computer
I used the following code with foreach... and when I run the game... my computer freezes
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemySpawner : MonoBehaviour {
     public GameObject enemy;
     // Use this for initialization
     void Start () {
         foreach (Transform child in transform) {
             GameObject enemyObj = Instantiate (enemy, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
             enemyObj.transform.parent = transform;    
         }
     }
     
     // Update is called once per frame
     void Update () {
         
     }
 }
 
               It isn't the first time I used foreach and that happens...
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Pengocat · Jan 07, 2017 at 03:16 PM
It is an infinite loop since you make a new Gameobject and make it a child of this object which makes another child.... over and over. Perhaps this is what you want?
         var childCount = transform.childCount;
         for (int i = 0; i < childCount; i++)
         {
             var spawnPoint = new Vector3(0, 0, 0);
             GameObject enemyObj = Instantiate(enemy, spawnPoint, Quaternion.identity);
             enemyObj.transform.parent = transform;
         }
     }
 
              ow... I forgot to say... there are three GameObjects as children of this EnemySpawner where the enemies will be instantiated...
actually I found my mistake in another forum... the right is enemyObj.transform.parent = child; ins$$anonymous$$d of enemyObj.transform.parent = transform;
but thanks anyway... I will test your script later...
Your answer