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



我有一个预制件,我将其添加到列表中,其中介于游戏功能之间。但是它永远不会停止添加游戏对象。

addtopath(( for循环中,每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);
        }
    }

}

它看上去不清楚您要在这里做什么,但是问题肯定是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);
    }
}

最新更新