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\$
  • 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\$ – UnholySheep Jan 11 '17 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 Jan 11 '17 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 Jan 11 '17 at 19:48
4
\$\begingroup\$

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

GameObject a = Instantiate(sparks,transform.position,transform.rotation);
Destroy(a, 2f);
| improve this answer | |
\$\endgroup\$
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);
    }
}
| improve this answer | |
\$\endgroup\$
  • 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 Jan 11 '17 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\$ – UnholySheep Jan 11 '17 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.