- Home /
Question by
SoulsReaper · Jun 13, 2015 at 01:29 PM ·
2dinstantiate2d gamerandom.rangeienumerator
Instantiate GameObject at Random time is not working
Whats up guys , I'm new to Unity and this is my first game so forgive my stupid question , 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 !
I put the script and a a screenshot to understand whats the problem exactly , Thanks for your time :)
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;
}
}
spam.png
(395.7 kB)
Comment
Answer by kevin-P951 · Jun 13, 2015 at 07:08 PM
do you mean looks like this?
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
public GameObject Spearman;
private float Timer;
// Use this for initialization
void Start ()
{
RandomTimer();
StartCoroutine(CallSpearman());
}
void SpawnSpearman()
{
Instantiate(Spearman,transform.position,transform.rotation);
}
void RandomTimer()
{
Timer = Random.Range(1.0f , 5.0f);
}
IEnumerator CallSpearman()
{
while(true)
{
SpawnSpearman();
yield return new WaitForSeconds(Timer);
RandomTimer();
}
}
}