Unity实例化列表中的对象并将其从列表和游戏中销毁

时间:2018-12-01 07:04:55

标签: c# unity3d

我试图在球体obj.z超过地形obj.z的中点时创建一块地形,并在它越过camera.z时将其删除。 由于一次创建了多个地形,因此我创建了一个地形列表:

 private List<nicoTerrain> terrains = new List<nicoTerrain>();

我在Start()实例化了其中的3个

    void Start () {
    terrains.Add(Instantiate(terrainOriginal));
    spawnPos += new Vector3(0, 0, terrainOriginal.transform.localScale.z/1.1f);
    terrains[terrains.Count - 1].transform.position = spawnPos;

    //create 2 more.
    terrains.Add(Instantiate(terrainOriginal));
    spawnPos += new Vector3(0, -30, -terrainOriginal.transform.localScale.z);
    terrains[terrains.Count - 1].transform.position = spawnPos;
    //Last one Bois
    terrains.Add(Instantiate(terrainOriginal));
    spawnPos += new Vector3(0, -30, -terrainOriginal.transform.localScale.z);
    terrains[terrains.Count - 1].transform.position = spawnPos;
    Debug.Log("got to the end of start bois");
}

但是我在更新时遇到了麻烦

    void Update () {
    sphereVel = sphere.GetComponent<Rigidbody>().velocity.z;
    if (terrains[terrains.Count - 2].transform.position.z > sphere.transform.position.z && sphereVel > 1){
        terrains.Add(Instantiate(terrainOriginal));
        spawnPos += new Vector3(0, -30, terrainOriginal.transform.localScale.z * sphereVel * 0.9f);
        terrains[terrains.Count - 1].transform.position = spawnPos;
    }
    else if(sphere.transform.position.z < terrains[terrains.Count - 2].transform.position.z - terrains[terrains.Count - 2].transform.localScale.z / 2)
    {
        terrains.Add(Instantiate(terrainOriginal));
        spawnPos += new Vector3(0, -30, -terrainOriginal.transform.localScale.z);
        terrains[terrains.Count - 1].transform.position = spawnPos;
    }
    if(terrains[0].transform.position.z > mainCamera.transform.position.z){
        Destroy(terrains[0]);
        terrains.Remove(terrains[0]);
    }
    Debug.Log("Sphere Velocity: " + sphereVel);
    Debug.Log("Terrains Count: " + terrains.Count);
}

destroy if语句“未设置为对象的实例”,而我的第一个if语句从不调用。我的“大于”和“小于”符号是相反的,因为sphere.z随着运动而减小。

0 个答案:

没有答案