我的协程并不是一个例行公事。为什么这个函数只调用一次?

时间:2015-09-16 18:37:17

标签: c# unity3d coroutine

我在团结游戏中编写了一个脚本来生成游戏对象。它使用协程。为什么我的spawnWaves()只调用一次?这是我的剧本:

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

    public GameObject[] hazards;
    public Vector3 spawnValues;
    public float spawnInterval;

    // Use this for initialization
    void Start ()
    {
        StartCoroutine(SpawnWaves(spawnInterval));
    }

    IEnumerator SpawnWaves(float interval)
    {
        Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
        Quaternion spawnRotation = new Quaternion(Random.Range(-Mathf.PI, Mathf.PI), Random.Range(-Mathf.PI, Mathf.PI), Random.Range(-Mathf.PI, Mathf.PI), Random.Range(-1f, +1f));
        Instantiate(hazards[Random.Range(0, 3)], spawnPosition, spawnRotation);

        yield return new WaitForSeconds(interval);
    }
}

Unity Editor中的所有公共值都已正确设置。

enter image description here

怎么了? 谢谢!

2 个答案:

答案 0 :(得分:4)

一个couroutine只是一个普通的yield - method。 使用循环while

while (...) 
{
    // Do work here
    yield return new WaitForSeconds(interval);
}

作为替代方案,我不推荐,你可以在最后再次启动协同程序。

....
yield return new WaitForSeconds(interval);
StartCoroutine(SpawnWaves(spawnInterval));

进一步解释

协程使用enumerator来运行上述代码。基本上,编译器会创建一个实现IEnumerator接口的后台类。 Jon Skeet很好地解释了here

答案 1 :(得分:1)

问题是你的方法只出现一次yield return并且它不在循环中。这意味着它始终返回一个IEnumerable对象,该对象从开始到结束包含(生成)单个项目。

您必须回答的问题是:您希望协程能够产生多少项?

如果您希望它只能产生一个项目,那么就可以了。

如果您希望它产生(例如)3个项目,它将看起来像这样:

yield return new WaitForSeconds(interval);
yield return new WaitForSeconds(interval);
yield return new WaitForSeconds(interval);

如果您希望它产生n个项目,它将类似于:

for(var i = 0; i < n; i++)
{
    yield return new WaitForSeconds(interval);
}

如果你希望它在满足条件之前屈服,那么你可能想要这样的东西:

while(!conditionIsMet)
{
    yield return new WaitForSeconds(interval);
}

如果您希望它产生可能无限量的物品:

while(true)
{
    yield return new WaitForSeconds(interval);
}