# Destroy object copies?

I want to know how to destroy object copies.

    public GameObject sparks;

void Update() {

}

void OnTriggerEnter(Collider bulletv) {

if (bulletv.gameObject.CompareTag("enemy"))
{
Destroy(this.gameObject);
Instantiate(sparks,transform.position,transform.rotation);
// destroy sparks copies after 2 seconds !!!
}
}

• What have you tried doing? You could just attach a simple script to the sparks that will "self-destruct" after 2 seconds – UnholySheep Jan 11 '17 at 18:57
• Thank you for your advice. Just I want to know how to destroy a copy of an object in this way. So, can you please answer the question ? – user43474 Jan 11 '17 at 19:11
• Have you looked at the documentation for Destroy? You can provide a second parameter to delay the destruction by some number of seconds. – DMGregory Jan 11 '17 at 19:48

Save a reference to the object you instantiate, like this:

GameObject a = Instantiate(sparks,transform.position,transform.rotation);
Destroy(a, 2f);


One of the simpler ways to destroy a gameobject after it has been instantiated is to use the Invoke method, in a similar way demonstrated in the documentation:

using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour {

void Start() {
Invoke("SelfDelete", 2);
}

void SelfDelete() {
Destroy(gameObject);
}
}

• Is there a reason not to use the built-in delay capability in the Destroy method for this? eg. Destroy(target, 2.0f); – DMGregory Jan 11 '17 at 19:47
• @DMGregory probably not - I remember I once had issues with it (but that was back in version 4.4) and used this way. I haven't used it with the built-in delay since then. (Actually I don't even remember if it had the delay back then - it's been too long) – UnholySheep Jan 11 '17 at 19:50