Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Instantiate a single object

Discussion in 'Scripting' started by mistergreed, Oct 18, 2022.

  1. mistergreed

    mistergreed

    Joined:
    Oct 4, 2022
    Posts:
    1
    This is my Code. I wanna spawn one Objekt but after TimeToSpawn its Generate Infinity Clone. Can help my anyone? I try it with WaitForSeconds but its make no difference.

    Code (csharp):
    1.  
    2.     [SerializeField] float TimeToSpawn = 7f;
    3.     [SerializeField] Transform[] spwanlokation;
    4.     [SerializeField] GameObject[] SpawnPrefab;
    5.     [SerializeField] GameObject[] SpawnClone;
    6.     float timer = 0f;
    7.  
    8.  
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.      
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         timer += Time.deltaTime;
    19.         if(timer > TimeToSpawn)
    20.         {
    21.             Spawny();
    22.         }
    23.  
    24.  
    25.     }
    26.  
    27.     IEnumerable SpawnControl()
    28.     {
    29.         yield return new WaitForSeconds(400F);
    30.     }
    31.  
    32.     public void Spawny()
    33.     {
    34.         SpawnClone[0] = Instantiate(SpawnPrefab[0], spwanlokation[0].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
    35.     }
    36. }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    9,404
    Well yes, look at the condition you use to decide if you need to spawn:
    Code (CSharp):
    1. if(timer > TimeToSpawn)
    When this becomes true, it should be pretty obvious that it's always true from then on so you'll always spawn each frame.
     
    Nad_B likes this.
  3. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    194
    So what @MelvMay is saying, is that you should reset the timer to zero after you spawn, or else it'll always be greater than TimeToSpawn. That's basically how countdowns work in programming.