- Home /
Make delay for spawn
Hello! How I can make delay for spawning mobs in function like -
function spawnSomething() {
var randomSpawn = new Vector3 (Random.Range(-5, 5), 5f, 0f);
Instantiate(onePrefab, randomSpawn, Quaternion.identity);
}
If insert yield WaitForSeconds (5), code wait 5 sec and start making objects without stop.
"start making objects without stop." this can be a pretty heavy task. Sure you don't want to limit the amount of monster? And do you want to spawn them in an interval or just as fast as possible?
Answer by HarshadK · Apr 09, 2014 at 01:24 PM
I guess you are trying to spawn objects continously over a specific time delay.
If so, you can use InvokeRepeating().
Like this:
InvokeRepeating("spawnSomething", 0.0f, 5.0f);
So that your specified function is called after amount of time delay specified.
Thanks for answer! But nothing is spawned, when i add this.
Answer by Patel-Sagar · Apr 09, 2014 at 01:24 PM
after adding yield, from where you are callong this function. you should not call it from Update or OnGUI. It should be called only once if you want to instantiate one. you should call it from start.
Answer by wacasce · Apr 09, 2021 at 10:43 AM
InvokeRepeating should work fine. But i suggest you use a for loop to limit the number of instantiated objects, unless if it is one of those endless runner / scrolling games, then you should set your objects to be destroyed after a certain period. try
int maxEnemies = 100;
void Start(){
InvokeRepeating("spawnSomething",0f,5f); //max # not included or you can use float to include
}
void spawnSomething(){
for (int i = 0; i < maxEnemies; i++){
//your spawn code here
}
}