【问题标题】:Restarting a Coroutine ignore the yield WaitForSeconds重启协程忽略 yield WaitForSeconds
【发布时间】:2023-03-26 07:01:01
【问题描述】:

我有一个协程的 IEnumerator,它会产生这样的对象

public IEnumerator spawnCoroutine;
private float spawnObstacleTimer;

void Start () {
        spawnObstacleTimer = GameObject.Find("EventSystem").GetComponent<gameManager>().spawnObstacleTimer;
        spawnCoroutine = spawnObsCoroutine(spawnObstacleTimer);
        startSpawnCoroutine();
    }

public IEnumerator spawnObsCoroutine(float timer)
    {
        while (true)
        {
            yield return new WaitForSeconds(timer);
            spawnObs();
        }
    }

public void startSpawnCoroutine()
    {
       StartCoroutine(spawnCoroutine);
    }
public void stopSpawnCoroutine()
    {
        StopCoroutine(spawnCoroutine);
    }

我在它运行良好的 Start() 上启动它。但是我已经设置了一个碰撞检测来在触发时停止这个协程。这再次运行良好,但是当我调用 OnCollisionExit() 时,它使用函数 startSpawnCoroutine() 重新启动协程;立即生成一个新对象并忽略yield return new WaitForSeconds()

那么这是怎么发生的呢? StopCouroutine 应该停止它,当我重新启动它时,它应该在执行生成之前等待几秒钟。

感谢您的帮助

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    函数StopCoroutine(spawnCoroutine) 可以更好地命名为PauseCoroutine(spawnCoroutine),当您再次调用start 时,它会从例程中的最后一个yield 重新启动。

    更改您的 startSpawnCoroutine() 函数以启动例程的新实例,使其“从头开始”

    public IEnumerator spawnCoroutine;
    private float spawnObstacleTimer;
    
    void Start () {
            spawnObstacleTimer = GameObject.Find("EventSystem").GetComponent<gameManager>().spawnObstacleTimer;
            startSpawnCoroutine();
        }
    
    public IEnumerator spawnObsCoroutine(float timer)
        {
            while (true)
            {
                yield return new WaitForSeconds(timer);
                spawnObs();
            }
        }
    
    public void startSpawnCoroutine()
        {
           //Moved the creation of the IEnumerable in to this function.
           spawnCoroutine = spawnObsCoroutine(spawnObstacleTimer);
           StartCoroutine(spawnCoroutine);
        }
    public void stopSpawnCoroutine()
        {
            StopCoroutine(spawnCoroutine);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2015-03-02
      • 2016-07-06
      • 2012-10-14
      • 1970-01-01
      • 2018-12-18
      • 2019-06-19
      • 1970-01-01
      • 2018-11-09
      相关资源
      最近更新 更多