简体   繁体   中英

Problems with IEnumerator WaitForSeconds in Unity

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?

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);
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM