如何保持协程直到条件为真 Unity

How to hold on coroutine until condition is true Unity

我的代码产生了一波又一波的敌人。例如,我有 3 波。他们每个人都有5个敌人。我使用协程生成它们。但与此同时,在第一波敌人产生后,紧接着下一波的初始化开始。但是第一波的敌人还没有完成他们的路线。因此,我想添加代码,使第二波的初始化在第一波的敌人从场景中消失后才开始。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    [SerializeField] List<WaveConfig> waveConfigs; // Here is config where i'm put a few waves ( for exmaple 3 waves with 5 enemies in each one)
    [SerializeField] int startingWave = 0;
    [SerializeField] bool looping = false;



    IEnumerator Start() //start courutine
    {
        do
        {
            yield return StartCoroutine(SpawnAllWaves());
        }
        while (looping);

    }


    private IEnumerator SpawnAllWaves() //coururent to spawn Enemies waves one by one
    {
        for (int waveIndex = startingWave; waveIndex < waveConfigs.Count; waveIndex++)
        {
            var currentWave = waveConfigs[waveIndex];
            yield return StartCoroutine(SpawnAllEnemiesInWave(currentWave)); //call coroutine to spawn all Enemies in wave.
        }

    }


    private IEnumerator SpawnAllEnemiesInWave(WaveConfig waveConfig) //Here is spawning each Enemies in particular wave
    {
        for (int enemyCount = 0; enemyCount < waveConfig.GetNumberOfEnemies(); enemyCount++)
        {
            var newEnemy = Instantiate(
                waveConfig.GetEnemyPrefab(),
                waveConfig.GetWaypoints()[0].transform.position,
                Quaternion.identity); //place enemy on scene
            newEnemy.GetComponent<EnemyPathing>().SetWaveConfig(waveConfig); //set them pay to move on scene
            yield return new WaitForSeconds(waveConfig.GetTimeBetweenSpawns()); //wait when next enemy in wave will generate

        }
    }

}

在你的敌人身上有一个 class 比如

public class Enemy : MonoBehaviour
{
    // Keeps track of all existing (alive) instances of this script
    private static readonly HashSet<Enemy> _instances = new HashSet<Enemy>();

    // return the amount of currently living instances
    public static int Count => _instances.Count;

    private void Awake ()
    {
        // Add yourself to the instances
        _instances.Add(this);
    }

    private void OnDestroy ()
    {
        // on death remove yourself from the instances
        _instances.Remove(this);
    }
}

然后您只需等待

private IEnumerator SpawnAllWaves()
{
    for (int waveIndex = startingWave; waveIndex < waveConfigs.Count; waveIndex++)
    {
        var currentWave = waveConfigs[waveIndex];
        yield return StartCoroutine(SpawnAllEnemiesInWave(currentWave));

        // After spawning all wait until all enemies are gone again
        yield return new WaitUntil(() => Enemy.Count == 0);
    }
}