我有一个预制件,我正在添加到一个列表与时间之间的游戏功能。然而,它从不停止添加游戏对象。
在addToPath()中,右边的for循环每2秒生成一个对象,但是如果我将其更改为任何其他数字,比如,这是我在列表中想要的总量,它将每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);
}
}
}发布于 2019-05-05 20:17:30
在我看来,这里不清楚您想做什么,但问题是,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);
}
}https://stackoverflow.com/questions/55995676
复制相似问题