- Home /
Using Yield Wait for seconds with instantiate
I'm trying to create a simple runner and have the game spawn a new enemy every 3 seconds, but when I use yield within a function instead of spawning a new enemy every 3 seconds, after 3 seconds the game doesn't stop spawning enemies. I'm betting it's something simpel but I'm not seeing it.
public var Spawn : GameObject;
function Update () {
CreateEnemy();
}
function CreateEnemy () {
var enemyInstance: GameObject;
yield WaitForSeconds(3.0);
enemyInstance = Instantiate(Spawn,transform.position,transform.rotation);
}
You are calling CreateEnemy() at every update. Assu$$anonymous$$g you are running at 60 fps, you stack up 180 coroutines before the first one does an Instantiate(), then one fire at approximately every 1/60 of a second as more are added.
Answer by karl_ · Aug 04, 2013 at 05:03 AM
This is because the Update function is calling 'CreateEnemy' as fast as it can continuously. Try this -
function Start()
{
InvokeRepeating("CreateEnemy", 0, 3);
}
function CreateEnemy()
{
var enemyInstance : GameObject;
enemyInstance = Instantiate(Spawn,transform.position,transform.rotation);
}
Relevant docs - http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.InvokeRepeating.html
Thanks for the help. Something tells me as I continue working on this that I'll be back with more questions :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613111514im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Waiting between pingpong loops 2 Answers
A node in a childnode? 1 Answer
WaitForSeconds... 2 Answers
Definition of Script.function() depends on Script.function()... 3 Answers
Why Is yield return new WaitForSeconds() not working 2 Answers