Search Unity

Just a simple question! please help!!!

Discussion in 'Scripting' started by Alexandher, Aug 21, 2014.

  1. Alexandher

    Alexandher

    Joined:
    Aug 11, 2014
    Posts:
    4
    So i have a simple question. I try to instantiate a prefab 5 times in the same place and something stupid happens the prefab gets spawned 9999++++ time and unity crashes. So the question! I do somethig wrong? or what? please help


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Test1 : MonoBehaviour {
    5.  
    6.     public Transform prefab;
    7.     public int howManyTImes = 5;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.        
    12.         for(int i  = 0; i < howManyTimes;  i++)
    13.         {
    14.             Instantiate(prefab);
    15.                 }
    16.    
    17.     }
    18.    
    19.     // Update is called once per frame
    20.     void Update ()
    21.    
    22.     {
    23.  
    24.     }
    25.  
    26. }
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Does the prefab have this script attached to it as well? If so, then each one that is spawned then spawns more and more.
     
    Alexandher likes this.
  3. Alexandher

    Alexandher

    Joined:
    Aug 11, 2014
    Posts:
    4
    well yes it has the script attached...but this solved my proble seems that i was blind thank you for helping!
     
  4. dakka

    dakka

    Joined:
    Jun 25, 2010
    Posts:
    113
    howManyTImes or howManyTimes...
     
  5. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    well then that's your problem. your creating more prefabs that are creating more and more prefabs. this script needs to be attached to a empty game object, your prefab that your spewing can't have this script on
     
    Alexandher likes this.
  6. ardizzle

    ardizzle

    Joined:
    Mar 28, 2013
    Posts:
    86
    Yep thats the problem then. It is going like this.
    1. spawn a new object.
    2. spawn a new object and the other new object spawns a new object.
    3. spawn a new object and the other new object spawns a new object and the other other new object spawns a new object.
    and repeat. See the problem?

    The best thing for you to do is attach the script to somthing else in the scene. Maybe the main camera or an empty gameObject. I would go with the empty gameObject
     
    Alexandher likes this.
  7. Alexandher

    Alexandher

    Joined:
    Aug 11, 2014
    Posts:
    4
    thank you guys i solved the problem!