Oscar Reyes
Oscar Reyes

Reputation: 4352

Unity Destroy GameObject instantiated clone

There's something I'm trying to achieve which is destroy an instantiated object (which is a Particle System). After doing some research, I found the way to instantiate and destroy the instantiated object is this:

public class CoinCollider : MonoBehaviour
{   
    public Transform coinEffect;

    void OnTriggerEnter(Collider info)
    {
        if (info.name == "Ball")
        {
            GameObject effect = GameObject.Instantiate(coinEffect, transform.position, transform.rotation) as GameObject;

            Destroy(effect);
            Destroy(gameObject);
        }
    }
}

but it seems not to delete it, this object is inherited to one object which is being destroyed. But after making this destroy. it seems to create another gameObject with name "Particle System(clone)" with no parent. How to delete it?

Upvotes: 2

Views: 17579

Answers (2)

Tuya Senff
Tuya Senff

Reputation: 3

This worked for me.

void DestroyProjectile() { Destroy(Instantiate(destroyEffect, transform.position, Quaternion.identity), 3f);

Upvotes: 0

axwcode
axwcode

Reputation: 7824

Problem

I found your problem and you are a victim of Unity being overprotective. You are trying to destroy the transform component of the clone, but you are not allowed to do that so Unity just ignores you.

Solution

void OnTriggerEnter(Collider info)
{
   if(info.name == "Ball")
      Destroy(Instantiate(coinEffect.gameObject, transform.position, transform.rotation), 5f);
}

So all you only need this one line. You Instantiate the gameObject component of the effect's transform. Then Destroy it using a timer, I gave it 5f, or else the effect would be destroyed instantaneously.

Upvotes: 4

Related Questions