Добавление игровых объектов в список навсегда - PullRequest
0 голосов
/ 05 мая 2019

У меня есть префаб, который я добавляю в список с временными интервалами для функциональности игры.Однако он никогда не прекращает добавлять игровые объекты.

В addToPath () цикл for тут же порождает 1 объект каждые 2 секунды, но если я изменю его на любое другое число, например 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 Ответ

2 голосов
/ 05 мая 2019

Мне неясно, что вы пытаетесь сделать здесь, но проблема определенно в том, что WaitAndPrint никогда не заканчивается, у него есть while (true) {...}, который не позволяет ему завершиться. Цикл не порождает объекты, WaitAndPrint is.

То, что вы, вероятно, хотите, это:

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

    }
}
...