添加游戏对象以永久列出问题

时间:2019-05-05 19:35:44

标签: c# unity3d coroutine

我有一个预制板,我将其添加到列表中,并在其中列出游戏功能的时间。但是,它永远不会停止添加游戏对象。

addToPath()循环中,每2秒产生1个对象,但是如果我将其更改为任何其他数字,例如 total ,这就是我想要的总数在列表中,它将每2秒添加那么多。

 public class FollowPath : MonoBehaviour
{
    public int total;
    public GameObject enemyAi;

    public List<GameObject> enemy;
    private IEnumerator coroutine;

    // Start is called before the first frame update
    void Start()
    {
        print("Starting " + Time.time);


        addToPath(enemyAi);
    }

    private void addToPath(GameObject ai) {
        for (int i = 0; i < 1; i++)
        {
            StartCoroutine(WaitAndPrint(2.0f, ai));
            print("Before WaitAndPrint Finishes " + Time.time);
        }  
    }

    // every 2 seconds perform the print()
    private IEnumerator WaitAndPrint(float waitTime, GameObject ai)
    {
        while (true)
        {
            yield return new WaitForSeconds(waitTime);
            print("WaitAndPrint " + Time.time);
            enemy.Add(ai);
            // Works for Object in Scene and Prefabs
            Instantiate(enemy[enemy.Count - 1], new Vector3(1, 1, 1), Quaternion.identity);

        }
    }


}

1 个答案:

答案 0 :(得分:2)

我似乎不清楚您要在此处做什么,但是明确的问题是WaitAndPrint从未完成,它有一个while (true) {...}不允许终止。循环不是生成对象,WaitAndPrint是。

您可能想要的是这样:

public class FollowPath : MonoBehaviour
{
    public int total;
    public GameObject enemyAi;

    public List<GameObject> enemy;
    private IEnumerator coroutine;

    // Start is called before the first frame update
    void Start()
    {
        print("Starting " + Time.time);


        StartCoroutine(addToPath(enemyAi));
    }

    private IEnumerator addToPath(GameObject ai) {
        for (int i = 0; i < 1; i++)
        {
            yield return new WaitForSeconds(waitTime);
            WaitAndPrint(2.0f, ai);
            print("Before WaitAndPrint Finishes " + Time.time);
        }  
    }

    private void WaitAndPrint(float waitTime, GameObject ai)
    {
        print("WaitAndPrint " + Time.time);
        enemy.Add(ai);
        // Works for Object in Scene and Prefabs
        Instantiate(enemy[enemy.Count - 1], new Vector3(1, 1, 1), Quaternion.identity);

    }
}