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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Spawning does not wait.

Discussion in 'Scripting' started by Lexo18, Apr 11, 2015.

  1. Lexo18

    Lexo18

    Joined:
    May 12, 2013
    Posts:
    34
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Spawner : MonoBehaviour {
    5.     bool spawn = true;
    6.     public int time = 2;
    7.     public GameObject enemyPrefab;
    8.     public int i;
    9.     public int amount;
    10.     // Use this for initialization
    11.     void Start () {
    12.  
    13.     }
    14.    
    15.     // Update is called once per frame
    16.     void Update(){
    17.         StartCoroutine(Timer ());
    18.    
    19.     }
    20.     //time the spawner.
    21.     IEnumerator Timer(){
    22.  
    23.         while (spawn){
    24.             yield return new WaitForSeconds(time);
    25.             time = Random.Range (3,6);
    26.             amount = Random.Range (1,4);
    27.             StartCoroutine(Spawn(amount));
    28.            
    29.         }
    30.     }
    31.     // spawn an amount of enemies.
    32.     IEnumerator Spawn(int amount){
    33.    
    34.         for(i=0;i<amount;i++){
    35.             yield return new WaitForSeconds((float)0.2);
    36.         Instantiate(enemyPrefab,transform.position,transform.rotation);
    37.         }
    38.         yield return new WaitForSeconds(time);
    39.     }
    40. }
    The problem is after the first wave of enemies being spawned it goes out of control and does not spawn them on the interval I told it to.
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    Since you are starting your coroutine from update, it will run it about 60 times per second - all the time. You probably want place your coroutine in "Start()".
     
  3. relic1882

    relic1882

    Joined:
    Mar 11, 2015
    Posts:
    45
    Coroutines run constantly on their own. Maybe put the StartCoroutine(Timer()); in your Start() function instead. It may be building up too much every frame and that's why it's going out of control.
     
  4. relic1882

    relic1882

    Joined:
    Mar 11, 2015
    Posts:
    45
    Beat me to it :) I had the same problem when I tried my first Coroutine. It crashed Unity on me every time I tried to run it and I couldn't figure out why. lol.