- Home /
Question by
artLightyear · Apr 03, 2014 at 08:55 AM ·
prefabrandomenemyspawncoroutines
Problem with random spawning and coroutine
Hello everyone. I'm actually pretty a newbie at coding, and I'm trying to figure out how to spawn a prefab randomly picked every x seconds (i've made a public float, so I can test the timing directly from inspector) - anyway, with the code i've written, the spawning begins after x seconds, and then starts to spawn prefabs every frame.
here's my code:
using UnityEngine;
using System.Collections;
public class Game_manager : MonoBehaviour {
public Transform[] teleport;
public GameObject[] prefeb;
public float waitTime;
IEnumerator SpawnPics() {
yield WaitForSeconds(waitTime);
int tele_num = Random.Range(0,2);
int prefeb_num = Random.Range(0,3);
Instantiate(prefeb[prefeb_num], teleport[tele_num].position, teleport[tele_num].rotation );
}
void Update(){
StartCoroutine("SpawnPics");
}
}
Can you help me figuring out where i'm going wrong?
thank you :)
Comment
Answer by Xypherorion · Apr 12, 2015 at 09:31 PM
In your code it is adding a new call to SpawnPics(), thus each FRAME it is waiting for waitTime seconds and Instantiating your new prefab, I would propose checking against an elapsed float before starting your coroutine:
using UnityEngine;
using System.Collections;
public class Game_manager : MonoBehaviour {
float Elapsed = 0.0f;
float WaitTime = 0.0f;
float MinTime = 0.0f;
float MaxTime = 5.0f;
IEnumerator SpawnPics() {
int tele_num = Random.Range(0,2);
int prefeb_num = Random.Range(0,3);
Instantiate(prefeb[prefeb_num], teleport[tele_num].position, teleport[tele_num].rotation );
}
void Update() {
Elapsed += Time.deltaTime;
if(Elapsed > WaitTime) {
Elapsed = 0.0f;
WaitTime = Random.Range(MinTime, MaxTime);
StartCoroutine("SpawnPics");
return yield null;
}
}
}