- Home /
Destroy object with OnTriggerExit
i'm new at scripting, trying to learn it myself, so i have a code that spawn selected prefab inside a trigger
public GameObject [] itemPrefabs;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
GameObject temp = Instantiate (itemPrefabs [Random.Range (0, itemPrefabs.Length)], transform.position, Quaternion.identity);
}
}
and i need to destroy spawned prefab when "player" exit the trigger without destroying spawner itself
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
Destroy ();
}
}
what do i need to write in Destroy function, or maybe use something else?
Answer by MacDx · Oct 01, 2017 at 11:17 PM
What you need to do is save a reference to the spawned game object so you can destroy it later inside your on trigger exit. I would do something like this.
First define a field like:
private GameObject spawnedPrefab;
then inside your OnTriggerEnterMethod replace the GameObject temp part with this new field, like this:
spawnedPrefab = Instantiate(itemPrefabs [Random.Range(0,itemPrefabs.Length)],transform.position,Quaternion.identity);
Finally, use the field as a parameter for the destroy method inside your OnTriggerExit, like this:
Destroy(spawnedPrefab);
If you want to have multiple prefabs spawned you will need to use a list of GameObjects instead, so you can save all the GameObject references you want and then iterate through the list to destroy each of them.
Hope this helps!