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

How do I make this code generate at set intervals?

Discussion in '2D' started by TurduckenMan, Apr 23, 2014.

  1. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Hey everyone, having some more issues!
    I'm trying to get objects to spawn at regular intervals but I'm not entirely sure how to modify this code to do it.

    Code (csharp):
    1.     public GameObject[] obj;
    2.     public float spawnMin = 1f;
    3.     public float spawnMax = 2f;
    4.  
    5.     // Use this for initialization
    6.     void Start () {
    7.         Spawn();
    8.     }
    9.    
    10.     // Update is called once per frame
    11.     void Spawn() {
    12.  
    13.         Instantiate(obj[Random.Range (0, obj.GetLength(0))], transform.position, Quaternion.identity);
    14.             Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
    15.     }
    16. }
    17.  
    As it is it spawns them a set amount of seconds, but no matter how much I fiddle with the min and max spawn settings I just can't make them stay even, any help would be greatly appreciated!
     
  2. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,987
    Well, they won't really be even because you are using a random number to determine the intervals.
    use:
    Code (csharp):
    1.  
    2.  
    3.     public GameObject[] obj;
    4.     public float spawnTime = 1f;
    5.  
    6.     void Start () {
    7.         Spawn();
    8.     }
    9.  
    10.     void Spawn() {
    11.         Instantiate(obj[Random.Range (0, obj.GetLength(0))], transform.position, Quaternion.identity);
    12.         Invoke ("Spawn",spawnTime);
    13.     }
    14. }
    15.  
    Then it will be consistent.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You should use InvokeRepeating.

    --Eric
     
  4. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Thanks guys! :D