首页 > 解决方案 > 如何统一从数组中仅实例化一个对象

问题描述

我想一次只实例化一个对象,所以我不知道我的代码有什么问题,因为它同时实例化了数组中的所有对象。使用随机范围是可能的,但我想按顺序将其实例化。

void Update()
    {
        if (timer > maxTime)
        {
           // Shuffle(enemies);

        //    RandomNumber = Random.Range(0, enemies.Length);
            float center = Screen.width / Screen.height;



            CreateEnemies(center);


          //  newEnemie = Instantiate(enemies[RandomNumber]);
          //   newEnemie.transform.position = transform.position+new Vector3(Random.Range(-screenBounds.x -1.5f, screenBounds.x +1.5f), 0, 0);
          //  newEnemie.transform.position = transform.position + new Vector3(Random.Range(-screenBounds.x + 1.5f, screenBounds.x - 1.5f), 0, 0);


            timer = 0;


        }

        timer += Time.deltaTime;
    }
    void Shuffle(GameObject[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            GameObject temp = array[i];
            int random = Random.Range(i, array.Length);
            array[i] = array[random];
            array[random] = temp;
        }
    }
    void CreateEnemies(float positionY)
    {
        for(int i = 0; i < enemies.Length; i++)
        {
            enemies[i] = Instantiate(enemies[i], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity)as GameObject;
            positionY += 1f;
        }
    }

标签: c#unity3d

解决方案


您的 create Enemies 函数执行所说的,它实例化敌人(复数)。当函数被调用时,它会遍历整个数组并实例化所有敌人。如果每次调用函数时只想要 1 ,则可以使用类似的东西。

private int currentEnemyIndex = 0;//Enemy to spwan index

void CreateEnemies(float positionY)
{
    if (currentEnemyIndex < enemies.Length)//Make sure you don't go out of bound for your array. You could also clamp if you want to keep spwaning the last one.
    {
        enemies[currentEnemyIndex] = Instantiate(enemies[currentEnemyIndex], transform.position + new Vector3(Random.Range(-screenBounds.x - 1.5f, screenBounds.x + 1.5f), 0, 0), Quaternion.identity) as GameObject;
        positionY += 1f;
        ++currentEnemyIndex;//Increment the enemy index so next call you spwan the next enemy.
    }
}

推荐阅读