0
\$\begingroup\$

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 !!!
    }
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ What have you tried doing? You could just attach a simple script to the sparks that will "self-destruct" after 2 seconds \$\endgroup\$ Commented Jan 11, 2017 at 18:57
  • \$\begingroup\$ 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 ? \$\endgroup\$
    – user43474
    Commented Jan 11, 2017 at 19:11
  • 2
    \$\begingroup\$ Have you looked at the documentation for Destroy? You can provide a second parameter to delay the destruction by some number of seconds. \$\endgroup\$
    – DMGregory
    Commented Jan 11, 2017 at 19:48

2 Answers 2

4
\$\begingroup\$

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

GameObject a = Instantiate(sparks,transform.position,transform.rotation);
Destroy(a, 2f);
\$\endgroup\$
0
1
\$\begingroup\$

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);
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is there a reason not to use the built-in delay capability in the Destroy method for this? eg. Destroy(target, 2.0f); \$\endgroup\$
    – DMGregory
    Commented Jan 11, 2017 at 19:47
  • \$\begingroup\$ @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) \$\endgroup\$ Commented Jan 11, 2017 at 19:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .