重新启动Coroutine会忽略yield WaitForSeconds

时间:2016-10-26 14:06:40

标签: c# unity3d coroutine

我有一个用于生成像这样的对象的协程的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()上启动它运行正常。但我已经进行了碰撞检测,以便在触发时停止此Coroutine。再次,这运行正常,但是当我调用OnCollisionExit()时,使用函数startSpawnCoroutine()重新启动Coroutine;一个新对象立即生成,忽略了yield return new WaitForSeconds()

那怎么发生? StopCouroutine应该全部停止,当我重新启动它时,它应该在执行产生之前等待几秒钟。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

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

更改您的startSpawnCoroutine()功能以启动例程的新实例,以便将其从头开始&#34;

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