要跟踪您实例化的对象,您可以创建一个List
of GameObject
,然后当您实例化一个对象时,您可以将其添加到List
. 然后,您可以使用GameObject
该列表中的任何内容来执行您需要的任何操作。
public GameObject[] arrows;
public float interval = 5;
private List<GameObject> myObjects = new List<GameObject>();
// Use this for initialization
void Start()
{
StartCoroutine(SpawnArrow());
}
public IEnumerator SpawnArrow()
{
WaitForSeconds delay = new WaitForSeconds(interval);
while (true)
{
GameObject prefab = arrows[UnityEngine.Random.Range(0, arrows.Length)];
GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
//Add the object to the list
myObjects.Add(clone);
yield return delay;
}
}
对于这样的生成对象,最好使用InvokeRepeating
,您可以将重复率传递给它,以及何时开始。有关 InvokeRepeating 的更多信息
这就是它的样子InvokeRepeating
public GameObject[] arrows;
public float interval = 5;
private List<GameObject> myObjects = new List<GameObject>();
// Use this for initialization
void Start()
{
InvokeRepeating("SpawnArrow", 0f, interval);
}
void SpawnArrow()
{
//Check if there's something in the list
if (myObjects.Count > 0)
{
//Destroy the last object in the list.
Destroy(myObjects.Last());
//Remove it from the list.
myObjects.RemoveAt(myObjects.Count - 1);
}
GameObject prefab = arrows[UnityEngine.Random.Range(0, arrows.Length)];
GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
//Add the object to the list
myObjects.Add(clone);
}
您可以销毁列表中最后一个生成的对象,方法是Destroy(myObjects.Last());
返回列表中的最后一个对象并销毁它。然后,您还应该将其从列表中删除myObjects.RemoveAt(myObjects.Count - 1);