Unity WaitForSeconds Not Working Inside Update or a Loop
I am trying to instantiate an object continuously. To do this, I need to have some sort of interval or wait timer so it doesn't instantiate everything at once. I came up with this:
public class EnemySpawner : MonoBehaviour
{
public GameObject Enemy;
public void Update()
{
var random = new Random();
var randomX = random.Next(-12, 12);
var randomY = random.Next(-5, 5);
StartCoroutine(Spawn(randomX, randomY));
}
public IEnumerator Spawn(int randomX, int randomY)
{
yield return new WaitForSeconds(3);
Instantiate(Enemy, new Vector3(randomX, randomY), Quaternion.identity);
}
}
What ends up happening is that it will wait for 3 seconds (as coded) and then instantiate as many objects as it can at once. The result I was hoping for was that it would spawn one, wait three seconds, spawn another one etc... Any information would be greatly appreciated!
Answer by gjf · Dec 06, 2019 at 06:43 PM
wrap your wait & Instantiate in a while loop...
while (true)
{ ... }
Answer by Larry-Dietz · Dec 06, 2019 at 07:43 PM
You are starting that coroutine multiple times, once each update cycle. So by the time your 3 seconds are up, they are up in a LOT of instances of the coroutine.
If you want one object spawned every three seconds, I would change your Spawn method to just a void, not a coroutine, Remove the StartCoroutine from Update and move those randoms into the spawn method, since it is what needs these values, then in Start, use
InvokeRepeating("Spawn", 3, 3);
to call it once, in 3 seconds, and again every 3 seconds thereafter.