如何在不停止的情况下多次执行Couroutine?

时间:2019-06-06 19:54:12

标签: c# unity3d ienumerator

我有一系列游戏对象,它们是灯光,我试图随着时间的推移增加和减小点光源的范围大小,问题是灯光有时并不会随着时间的推移而减少,它们只是立即达到范围0。

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

public class MainMenu : MonoBehaviour
{
    public GameObject[] stars;

    private void Start()
    {
        StartCoroutine(ChooseStar());
    }

    public void PlayGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }

    public void QuitGame()
    {
        Application.Quit();
    }


    IEnumerator IncreaseRadius(GameObject star, float duration)
    {
        Debug.Log("Increasing: "+star.name + " radius: " + star.GetComponent<Light>().range);
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            star.GetComponent<Light>().range = counter;
            yield return null;
        }
        StartCoroutine(DecreaseRadius(star));
    }

    IEnumerator DecreaseRadius(GameObject star)
    {
        Debug.Log("Decreasing: "+star.name+" radius: "+ star.GetComponent<Light>().range);
        float counter = star.GetComponent<Light>().range;

        while (star.GetComponent<Light>().range >= 0f)
        {
            counter -= Time.deltaTime;
            star.GetComponent<Light>().range = counter;
            yield return null;
        }
        star.GetComponent<Light>().range = 0f;

    }

    IEnumerator ChooseStar()
    {
        float duration = Random.Range(3, 8);
        float waitTime = 2f;

        GameObject choosenStar = stars[Random.Range(0, stars.Length)];

        if (choosenStar.GetComponent<Light>().range <= 0f)
        {
            StartCoroutine(IncreaseRadius(stars[Random.Range(0, stars.Length)], duration));
        }
        else
        {
            waitTime = 0f;
        }

        yield return new WaitForSeconds(waitTime);
        StartCoroutine(ChooseStar());

    }
}

预期结果应为以下顺序:

1-从游戏对象数组中选择随机星星 2-检查是否已增加恒星范围,如果是,则再次开始搜索新星,如果否开始增加。 3-指示灯开始增加直到持续时间,然后调用减少功能 4-星开始减少,当功能超过它时,将范围重置为0

1 个答案:

答案 0 :(得分:2)

一般来说,要回答这个问题:您只需输入

while (true)
{
   ... 

   yield return ...
}

围绕您的代码。只要您yield在其中某处对协程完全有效。


我的猜测是,您会获得并发的协同程序,因为您不必等待IncreaseRadius完成之后再选择下一个随机星...这可能与之前相同。

if (chosenStar.range <= 0f)
{
    StartCoroutine(IncreaseRadius(stars[Random.Range(0, stars.Length)], duration));
}
else
{
    waitTime = 0f;
}

您也可以在此处再次执行“ Random.Range”,尽管您之前已经选择了另一颗星,这是故意的吗?


通常首先使用而不是一遍又一遍地使用GetComponent<Light>而不是简单地

public Light[] stars;

以与以前相同的方式引用对象,但是现在您直接处理Light引用,而不是GameObject

那你知道

float duration = Random.Range(3, 8);

实际上返回int3之间的随机完整7值。如果您想同时在float3之间设置8值,则还应包括例如3.253453f,那么您宁可使用

var duration = Random.Range(3.0f, 8.0f);

解决方案1-一次仅一颗星

作为一种简单的替代方法,您始终只能一次设置一颗星星的动画。您可以通过另外yield return IEnumerator个来实现。这使另一个IEnumerator执行并同时等待它完成。像

public Light[] stars;

private void Start()
{
    StartCoroutine(ChooseStar());
}

private IEnumerator IncreaseRadius(Light star, float duration)
{
    Debug.Log("Increasing: " + star.name + " radius: " + star.range);
    float counter = 0;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        star.range = counter;
        yield return null;
    }

    // again do the decreasing and at the same time wait for it to finish
    yield return DecreaseRadius(star);
}

private static IEnumerator DecreaseRadius(Light star)
{
    Debug.Log("Decreasing: " + star.name + " radius: " + star.range);
    var counter = star.range;

    while (star.range >= 0f)
    {
        counter -= Time.deltaTime;
        star.range = counter;
        yield return null;
    }
    star.range = 0f;
}

IEnumerator ChooseStar()
{
    // Looks scary but is totally fine in Coroutines as long as you yield somewhere
    // instead of starting a new Coroutine simple continue the one you already have
    while (true)
    {
        var duration = Random.Range(3.0f, 8.0f);

        var choosenStar = stars[Random.Range(0, stars.Length)];

        // This starts the Increase routine on that star
        // and at the same time waits for it to finish!
        //
        // since we also wait until DecreaseRadius is done this means 
        // at any time only exactly 1 star is animated at the same time
        yield return IncreaseRadius(choosenStar, duration);
    }
}

解决方案2-过滤随机

或者,您看起来像想要,以允许对星星进行并行动画处理,我只过滤掉可用星星列表(当前未动画的星星)以获取随机范围。像

public Light[] stars;

// Use a list for dynamically adding and removing items
private List<Light> availableStars = new List<Light>();

private void Start()
{
    // initialize the available list
    // copy the references from stars
    availableStars.AddRange(stars);

    StartCoroutine(ChooseStar());
}

private IEnumerator IncreaseRadius(Light star, float duration)
{
    Debug.Log("Increasing: " + star.name + " radius: " + star.range);

    // As soon as you start animating this star
    // remove it from the list of availables
    availableStars.Remove(star);

    float counter = 0;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        star.range = counter;
        yield return null;
    }

    // Decreasing and at the same time wait for it to finish
    yield return DecreaseRadius(star);

    // when finished add the star again to the availables
    availableStars.Add(star);
}

private static IEnumerator DecreaseRadius(Light star)
{
    Debug.Log("Decreasing: " + star.name + " radius: " + star.range);
    var counter = star.range;

    while (star.range >= 0f)
    {
        counter -= Time.deltaTime;
        star.range = counter;
        yield return null;
    }
    star.range = 0f;
}

IEnumerator ChooseStar()
{
    // Looks scary but is totally fine in Coroutines as long as you yield somewhere
    while (true)
    {
        var duration = Random.Range(3.0f, 8.0f);

        // in case that currently all stars are being animated
        // simply wait until the next one becomes available again
        yield return new WaitUntil(() => availableStars.Count > 0);

        // Pick a random star from the availables instead
        var chosenStar = availableStars[Random.Range(0, availableStars.Count)];

        // this check becomes then actually redundant
        //if (chosenStar.range <= 0f)
        //{
        StartCoroutine(IncreaseRadius(chosenStar, duration));
        yield return new WaitForSeconds(2f);
        //}
    }
}