Search Unity

Trying to create gameobjects at intervals [C#]

Discussion in 'Scripting' started by dsillman2000, Jul 3, 2015.

  1. dsillman2000

    dsillman2000

    Joined:
    Feb 23, 2014
    Posts:
    5
    Hey guys,
    my current challenge is trying to instantiate "enemy" gameobjects at 2 second intervals. However, when I try to use the "waitForSecond" type function, they are simply instantiated MANY TIMES and nearly crashes unity. Ideally, my (pseudo)code would look like this:

    void Update()
    {
    waitForSeconds(2);
    gameObject.instantiate("Enemy");
    }
     
  2. Pavlon

    Pavlon

    Joined:
    Apr 15, 2015
    Posts:
    191
    that is what i use for the moment

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class WaveSpawningScript : MonoBehaviour {
    5.  
    6.     public  GameObject     spawn_point;
    7.     public  int         wave_size     = 5;
    8.     public     int            mul = 1;
    9.     private float         spawn_rate     = 2.5f;
    10.     private float         next_spawn     = 0.0f;
    11.  
    12.     public void Update_()
    13.     {
    14.         if(Time.time >= next_spawn && wave_size != 0)
    15.         {
    16.             SpawnMonster();
    17.         }
    18.     }
    19.  
    20.     private void SpawnMonster()
    21.     {
    22.  
    23.             next_spawn =  Time.time + spawn_rate;
    24.             wave_size --;
    25.             GameObject monster = Instantiate(Resources.Load("Monster/Slime/SlimeMonster"),spawn_point.transform.position,Quaternion.AngleAxis(180,new Vector3(0,1,0))) as GameObject;
    26.             monster.GetComponent<Monster>().life = 20 * mul;
    27.     }
    28. }
    29.  
    Update_ is called from the main loop when needed
     
  3. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    Code (csharp):
    1. InvokeRepeating
     
  4. dsillman2000

    dsillman2000

    Joined:
    Feb 23, 2014
    Posts:
    5
    Thanks for the help, guys!