Ich habe ein Array, um mehrere Spielobjekte zu instanziieren, wenn der Spieler einen Trigger eingibt, aber ich weiß nicht, wie man diese GameObjects zerstört, wenn der Spieler den Trigger verlässt. Dies ist mein Code:Zerstöre die Spielobjekte eines Arrays
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);
}
}
}
UPDATE CODE:
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));
}
}
}
Obwohl ich das mag, denke ich, es gibt einen Tippfehler. 'instantiated.Add (Instantiate (spawnObjects [selection], spawnPosition.transform.position, spawnPosition.transform.rotation));' sollte 'instanziiert sein.Add (Instantiate (prefab, spawnPosition.transform.position, spawnPosition.transform.rotation)); ' – Programmer
@Programmer Ich denke,' spawnObjects' soll eine Liste von Prefabs sein. Wenn nicht, muss dies natürlich geändert werden. –
@GunnarB. Ich habe es getestet und diese Fehler angezeigt: Assets/0_asm/Scripts/SpawnDestroy.cs (44,38): Fehler CS1502: Die beste überladene Methode für 'System.Collections.Generic.List .Add (UnityEngine.GameObject) 'hat einige ungültige Argumente Assets/0_asm/Scripts/SpawnDestroy.cs (44,38): Fehler CS1503: Argument '# 1' kann 'UnityEngine.Object' Ausdruck nicht in Typ' UnityEngine.GameObject 'konvertieren –
Angelsm