Cloned objects won't get destroyed if created in a short period of time

using UnityEngine;

public class PlayerJump : MonoBehaviour
{
    //variants
    public GameObject explosionEffect;
    public float radius = 10f;
    public float force = 700f;


    void Update()
    {
        //User input key
        if (Input.GetKeyDown("space"))
        {
            Explode();
        }
    }

//Basically from now on when pressing space an explosive force will be applied, affecting the objects nearby and make the player jump as well, followed by a particle animation

    void Explode()
    {
        Instantiate(explosionEffect, transform.position, transform.rotation);

        //Applying force to rigidbodies nearby (correct me if I'm wrong)
        Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
        foreach (Collider nearbyObject in colliders)
        {
            Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
            if(rb != null)
            {
                rb.AddExplosionForce(force, transform.position, radius);
            }
        }


//And this is supposedly where the cloned particles would be destroyed

        //Destroying the cloned object (particles)
        Destroy(GameObject.Find("Explosion(Clone)"), 1);
    }
}

Don’t use GameObject.Find. It might find the explosion you just created, or it might find a completely different explosion. They all have the same name, so it just picks one at random essentially. It’s also a very slow function because it searches the whole scene.

Luckily there’s no need to use Find at all here. Instantiate returns a reference directly to the newly created object, so you can just use that. You just need to do this:

GameObject explosionInstance = Instantiate(explosionEffect, transform.position, transform.rotation);

// other code here...

Destroy(explosionInstance, 1);
2 Likes

Thank you so much!!! It works completely fine now :wink: