【问题标题】:Adding Game Objects to list forever problem添加游戏对象以永久列出问题
【发布时间】:2019-05-05 19:35:43
【问题描述】:

我有一个预制件,我正在将其添加到一个列表中,其中包含用于游戏功能的时间安排。但是它永远不会停止添加游戏对象。

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

        }
    }


}

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    我看不清楚你在这里要做什么,但问题是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);
    
        }
    }
    

    【讨论】:

    • 看了这么久我想念我的循环,现在我听到了,这很有意义
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多