hi fellas i have problem i want to instantiate an enemy and delay and instatiate again and it will continioue for ever but the couroutine not work in update()
but because of enemy instatiatiation must occur in update method i must write its code on update() but unfortunatly i dont know what to do with couroutine because it happen one time and never continoue please help me
void Update()
{
StartCoroutine(delay(1));
}
IEnumerator delay(float delay)
{
yield return new WaitForSeconds(delay);
Instantiate(enemyprefab1, new Vector3(enemyprefab1.transform.position.x, Random.RandomRange(-26f, 13f), enemyprefab1.transform.position.z), Quaternion.Euler(90, 90, 0));
}
Bunny83
September 1, 2012, 2:41pm
2
It works perfectly, you just start a new coroutine every frame. Each coroutine will wait 1 sec and then instantiate your prefab.
You can’t wait in Update, if you want to instantiate one prefab every second, do something like this:
void Start()
{
StartCoroutine(SpawnEnemies(1.0f));
}
IEnumerator SpawnEnemies(float aDelay)
{
Vector3 pos = enemyprefab1.transform.position;
while (true)
{
yield return new WaitForSeconds(aDelay);
pos.y = Random.RandomRange(-26f, 13f);
Instantiate(enemyprefab1, pos, Quaternion.Euler(90, 90, 0));
}
}
Another way would be to use InvokeRepeating (which would be Fattie’s choice ;))
void Start()
{
InvokeRepeating("SpawnEnemy", 1.0f, 1.0f);
}
void SpawnEnemy()
{
Instantiate(enemyprefab1, new Vector3(enemyprefab1.transform.position.x, Random.RandomRange(-26f, 13f), enemyprefab1.transform.position.z), Quaternion.Euler(90, 90, 0));
}