Ophélia Ophélia - 10 months ago 60
C# Question

destroy a specific gameobject after an amount of time in unity

I kinda stuck with my script right now. When a gameObject, with my script attached to it, has a trigger event with a specific gameObject, I want to destroy the specific gameObject after an amount of time.

So i came to this:

void OnTriggerEnter ( Collider other) {

if (other.gameObject.tag == "leaf1"){
StartCoroutine (LeafDestruction ());

IEnumerator LeafDestruction(){

yield return new WaitForSeconds (5);
Destroy (gameObject);


I know it's a noob mistake but i think i miss something, because when i run this script, it destroys the gameObject with the script attached to it, and not the specific gameObject(with tags).

How can i fix that?

Answer Source

A simpler solution is to use the 2nd parameter of the Destroy function :

if (other.gameObject.tag == "leaf1")
      Destroy( other.gameObject, 5.0f ) ;