统一生成对象

Spawn objects in unity

我正在使用 C# 在 Unity 中编写一个小型 2D 游戏。我建造了两个生成垂直线的障碍生成器。线条生成后,它们会向下移动。其中一个产卵器位于左上边缘,另一个位于右上边缘。目前,新对象会在一定时间后生成。但是我的目标是,例如,当在右上角生成的对象已经移动了一定距离时,在左上角边缘生成一个新对象。 这可能通过对象的坐标来完成吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObstacleSpawner : MonoBehaviour
{
    public GameObject[] obstacles;
    public List<GameObject> obstaclesToSpawn = new List <GameObject>();
    int index;

    void Awake()
    {
        InitObstacles();
    }

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine (SpawnRandomObstacle ());
    }

    // Initialize obstacles
    void InitObstacles()
    {
        index=0;
        for(int i =0; i<obstacles.Length*3;i++){
        GameObject obj = Instantiate(obstacles[index], transform.position, Quaternion.identity);
        obstaclesToSpawn.Add(obj);
        obstaclesToSpawn [i].SetActive (false);
        index++;

            if (index == obstacles.Length)
            {
                index= 0;
            }
        }
    }

    IEnumerator SpawnRandomObstacle()
    {
        //Wait a certain time
        yield return new WaitForSeconds(3f);
    }


            //I want something like this
            (if gameObject.x == -0.99){



            //activate obstacles
            int index = Random.Range(0, obstaclesToSpawn.Count);

            while(true){
                if (!obstaclesToSpawn[index].activeInHierarchy){
                    obstaclesToSpawn[index].SetActive(true);
                    obstaclesToSpawn [index].transform.position = transform.position;
                    break;
                }else{
                    index = Random.Range (0, obstaclesToSpawn.Count);
                }
            }

            StartCoroutine (SpawnRandomObstacle ());
        }
    }

据我了解,您需要在每个生成器中保存对其他生成器的引用。

public class ObstacleSpawner : MonoBehaviour
{
    public ObstacleSpawner otherSpawner;
    ...

然后在生成器中检查第二个生成器中障碍物的位置。像这样:

...
if (otherSpawner.obstaclesToSpawn[someIndex].transform.position.x <= -0.99)
{
    // Spawn new obstacle in this spawner...
    ...
}

将对象的位置与世界中的某个位置进行比较现在可能对您有用,但如果您尝试更改场景的设置方式,将来可能会出现问题。

您正在寻找一个物体移动的距离,并且您拥有计算所述距离所需的一切。

ObstacleSpawner 生成的所有障碍物的起点是 ObstacleSpawner 对象的位置,因此您无需缓存生成位置,这让事情变得容易多了。

您需要一个变量来定义您想要生成另一个障碍物的距离,例如 public float distBeforeNextObstacle = 1f,然后您可以将此距离与障碍物与其生成位置的距离进行比较(使用 Vector3Vector2,两者都有一个Distance方法,你应该选择最适合你的游戏的方法):

if(Vector3.Distance(obstaclesToSpawn[index].transform.position, transform.position)>=distBeforeNextObstacle)
{
    //Spawn next obstacle
}