- Home /
WaitForSeconds Error
Hey! I've been trying to spawn enemies every five seconds with Instantiate, but the code keeps on giving me an error when I try. Any answers?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Spawn : MonoBehaviour {
public float startPositionX;
public float startPositionY;
public float startPositionZ;
public GameObject enemyObject;
void Start ()
{
for(int i = 0; i < 10; i++)
{
Instantiate(enemyObject, new Vector3(0, startPositionY, Random.Range(0f, -20f)), Quaternion.identity);
StartCoroutine(Wait);
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(5);
}
}
Answer by Tsequier · Mar 08, 2018 at 06:42 PM
A coroutine is executed on a separated thread, so your code in your for
won't wait for 5 seconds and will spawn all enemies in one frame.
If you want to spawn enemies with a 5 seconds delay, you need to put the Instantiate function in a coroutine as well.
For example, something like
IEnumerator Wait()
{
for(int i = 0; i < 10; i++)
{
Instantiate(enemyObject, new Vector3(0, startPositionY, Random.Range(0f, -20f)), Quaternion.identity);
yield return new WaitForSeconds(5);
}
}
and your Start function will look like something like this
void Start()
{
StartCoroutine(Wait());
}
(Note that if the code you provided you forgot the "()" after your method name in StartCoroutine)
Hope this helps !
Note: a coroutine is not executed in a separate thread. Unity runs in a unique thread, coroutines included.
You are absolutely right, I made a unnecessary shortcut thinking it would help the understanding of the problem, my bad!