Reputation: 101
So Im trying to destroy enemies in a while loop, waiting 1 second in between (can they make waiting a bit harder??) Problem is, all enemies are getting destroyed at the same time, theyre not waiting for WaitForSEconds. In my while loop I call each enemy by their tag, which goes from Enemy1 to Enemy5. Heres my code.
void OnTriggerEnter(Collider otherObject)
{
int i=1;
while (i<=numenemies)
{
string tag="Enemy"+i;
destroyenemy=GameObject.FindGameObjectWithTag(tag);
Destroy(destroyenemy);
i++;
StartCoroutine(DestroyWait ());
}
}
IEnumerator DestroyWait()
{
Debug.Log ("so far...");
yield return new WaitForSeconds (1);
Debug.Log ("so good");
}
In my console from my debug log, Im getting 4 "so far..." and then 4 "so good". its not waiting for 1 sec then outputing so good.
Ive been reading up on this and man its so hard to just pause the script for 1 second! what am i doing wrong?
Upvotes: 1
Views: 5898
Reputation: 15951
Move all your code inside a coroutine:
void OnTriggerEnter(Collider otherObject)
{
StartCoroutine(DestroyAllEnemies());
}
IEnumerator DestroyAllEnemies()
{
for(int i = 1; i<=numenemies;i++)
{
string tag="Enemy"+i;
destroyenemy=GameObject.FindGameObjectWithTag(tag);
Destroy(destroyenemy);
yield return new WaitForSeconds (1);
}
}
Upvotes: 2