Amjad Mesmar
Amjad Mesmar

Reputation: 86

Instantiate GameObject at Random time is not working

I want the enemy to spawn at random time between 1-5 seconds but when I applied the script inside the game , the game is spammed with enemies and it continuously nonstop spawning enemies !

enter image description here

 using UnityEngine; using System.Collections;

 public class Game_Control : MonoBehaviour {

     private bool Spawn1=true;
     public GameObject Spearman;
     private float STimer;

     void Start () {
         STimer =  Random.Range(1f,5f);
     }

     void Update () {
         if (Spawn1 = true) {
             Instantiate (Spearman, transform.position, transform.rotation);
             StartCoroutine (Timer ());
         } 
     }

     IEnumerator Timer() {
         Spawn1 = false;
         yield return new WaitForSeconds (STimer);
         Spawn1=true;
     }
 }

Upvotes: 2

Views: 932

Answers (1)

mayo
mayo

Reputation: 4075

seems like inside Update you are missing a '='

Ie:

if (Spawn1 = true) 

Should be:

if (Spawn1 == true)

Also to avoid extra processing on Update method you can do this:

void Start() 
{
    StartCoroutine(AutoSpam());
}

void Update() 
{
    // Empty :),
    // but if your Update() is empty you should remove it from your monoBehaviour! 
}

IEnumerator AutoSpam() 
{
    while (true)
    {
        STimer = Random.Range(1f,5f);
        yield return new WaitForSeconds(STimer);
        Instantiate(Spearman, transform.position, transform.rotation);
    }
}

Upvotes: 4

Related Questions