销毁数组的游戏对象

时间:2016-10-22 11:56:19

标签: c# unity3d unity5

当玩家进入触发器时,我有一个数组来实例化多个游戏对象,但是当玩家退出触发器时我不知道如何销毁这些游戏对象。这是我的代码:

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

public class SpawnDestroy : MonoBehaviour {

public List<GameObject> spawnPositions;
public List<GameObject> spawnObjects;


void OnTriggerEnter(Collider other)
{

    if (other.gameObject.tag == "Player")
    {
        SpawnObjects ();
    }
}

void OnTriggerExit(Collider other)
{

    if (other.gameObject.tag == "Player")
    {

    ............

    }
}

void SpawnObjects()
{
    foreach(GameObject spawnPosition in spawnPositions)
    {
        int selection = Random.Range(0, spawnObjects.Count);
        Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation);
    }
}

}

更新代码:

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


public class SpawnDestroy : MonoBehaviour {

public List<GameObject> spawnPositions;
public List<GameObject> spawnObjects;
private List<GameObject> instantiated;


void OnTriggerEnter(Collider other)
{

    if (other.gameObject.tag == "Player")
    {
        SpawnObjects ();
    }
}

void OnTriggerExit(Collider other)
{

    if (other.gameObject.tag == "Player")
    {

        for(int i = 0; i < instantiated.Count; i++)
        {
            Destroy(instantiated[i]);
        }

        }
}

void SpawnObjects()
{
    // (re-)initialize as empty list
    instantiated = new List<GameObject>();

    foreach(GameObject spawnPosition in spawnPositions)
    {
        int selection = Random.Range(0, spawnObjects.Count);
        instantiated.Add(Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation));
    }
}

}

1 个答案:

答案 0 :(得分:2)

目前,您不存储对实例化游戏对象的引用。

为此您可以创建另一个列表并添加实例化对象,类似这样(这是一个简短的版本,您也可以将它们存储在临时文件中):

private List<GameObject> instantiated;

...

void SpawnObjects()
{
    // (re-)initialize as empty list
    instantiated = new List<GameObject>();

    foreach(GameObject spawnPosition in spawnPositions)
    {
        int selection = Random.Range(0, spawnObjects.Count);
        instantiated.Add((GameObject)Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation));
    }
}

然后摧毁:

for(int i = 0; i < instantiated.Count; i++)
{
    Destroy(instantiated[i]);
}

还有其他方法。例如。如果您不想每次都重新初始化列表,则可以在销毁之前从列表中删除这些项目。在这种情况下,您需要从后到前迭代列表。 (另外,如上所述,如果对象被明显破坏,你不得试图从列表中引用某些东西,因为这会引起错误。)

另一种方法是在实例化时将游戏对象作为子对象添加到某个父对象并迭代它们以进行销毁,例如

while(parentTransform.childCount > 0)
{
    Transform child = parentTransform.GetChild(0);
    Destroy(child.gameObject);
    child.SetParent(null);
}
相关问题