Search code examples
c#unityscriptunity-game-engine

Why my unity program froze when trying to create multiple gameobjects by c# script?


I have in the Hierarchy two ThirdPersonControllers. And i create new c# script file then dragged the script to the first ThirdPersonController.

It should clone more 10 ThirdPersonControllers of the first ThirdPersonController.

This is the script:

using UnityEngine;
using System.Collections;

public class Multiple_objects : MonoBehaviour {

    public GameObject prefab;
    public GameObject[] gos;

    void Awake()
    {
        gos = new GameObject[10];
        for(int i = 0; i < gos.Length; i++)
        {
            GameObject clone = (GameObject)Instantiate(prefab, Vector3.zero, Quaternion.identity);
            gos[i] = clone;
        }
    }

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
}

In the Inspector of the ThirdPersonController in the script area in the Prefab i selected the ThirdPersonController.

But when running the game the Unity the whole program is frozed i had to use Task Manager to shut it down. I know its the script the problem since i tried it without the script and it was fine.

What i want to do is instead 2 ThirdPersonControllers to have when running the game 10 or 20 ThiredPersonControllers each one in another position by using the c# script.

Screenshot of my Hierarchy:

Hierarchy


Solution

  • From what I'm seeing looks like the prefab you are initializing has the "Multiple_objects" Script, so this means every new instance is going to execute that script and create 10 more and so on.

    Try putting "Multiple_objects" Script on another GameObject thats not going to be dynamically initialized. (ex: An empty GameObject, Main Camera, Directional Light).