如何将Coroutine法案视为更新

时间:2016-05-18 00:14:09

标签: c# unity3d coroutine

有人告诉我,当我不需要使用更新时,我不应该使用更新。我不确定何时不使用它们,但我想弄清楚它。

我希望有一个事件,“Wave”,运行20秒然后切换到随机的“Wave”并再运行20秒并继续重复此循环。

游戏经理:

void Start()
{
    StartFireWaves();
}

public void StartFireWaves()
{
    StartCoroutine(wm.SelectWave());
}

Wave Manager:

public IEnumerator SelectWave()
{

   float waitFor;
   float diff = 0;

    diff = nextWaveAT - Time.time;

    if (diff <= 0f)
    {
        SpawnFlames();
        waitFor = Random.Range(15, 20);

    }
    nextWaveAT = nextWaveAT + waitFor;
    yield return new WaitForSeconds(waitFor);
}

SpawnFlames:

void SpawnFlames()
{
    float val = Random.value;

    if (val < .25f)
    {
        Wave1();
    }
    if (val >= .25f && val < .5f)
    {
        Wave2();
    }
    if (val >= .5f && val < .75f)
    {
        Wave3();
    }
    else
    {
        Wave4();
    }
}

我假设它应该如何工作,但它似乎不会保持“更新”或运行。它只运行一次然后没有任何反应。

1 个答案:

答案 0 :(得分:2)

使用Coroutine多个嵌套while循环来执行此操作。第一个while循环是让它永远运行,直到调用stopRunningWaves()函数。第二个while循环用于在 x 时间内运行wave,然后跳回第一个while循环。

bool keepRunningWaves = false;
IEnumerator startingRunningWaves(float second = 20)
{
    if (keepRunningWaves)
    {
        yield break;
    }

    keepRunningWaves = true;

    while (keepRunningWaves)
    {

        float timer = 0;

        int randWave = Random.Range(1, 5);
        while (timer < second)
        {
            if (!keepRunningWaves)
            {
                yield break;
            }

            if (randWave == 1)
            {
                Debug.Log("Running Wave 1");
                Wave1();
            }
            else if (randWave == 2)
            {
                Debug.Log("Running Wave 2");
                Wave2();
            }
            else if (randWave == 3)
            {
                Debug.Log("Running Wave 3");
                Wave3();
            }
            else if (randWave == 4)
            {
                Debug.Log("Running Wave 4");
                Wave4();
            }

            timer += Time.deltaTime;
            yield return null;
        }
        //Reset Timer for next run 
        timer = 0;

        yield return null;
    }

   keepRunningWaves = false;
}

void stopRunningWaves()
{
    keepRunningWaves = false;
}

要测试它,请使用 3 秒来执行此操作,以便节省您的时间:

StartCoroutine(startingRunningWaves(3));