Search Unity

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

Discussion in 'Scripting' started by ImprobableDoge, Aug 19, 2021.

  1. ImprobableDoge

    ImprobableDoge

    Joined:
    Aug 4, 2021
    Posts:
    40
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerJump : MonoBehaviour
    4. {
    5.     //variants
    6.     public GameObject explosionEffect;
    7.     public float radius = 10f;
    8.     public float force = 700f;
    9.  
    10.  
    11.     void Update()
    12.     {
    13.         //User input key
    14.         if (Input.GetKeyDown("space"))
    15.         {
    16.             Explode();
    17.         }
    18.     }
    19.  
    20. //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
    21.  
    22.     void Explode()
    23.     {
    24.         Instantiate(explosionEffect, transform.position, transform.rotation);
    25.  
    26.         //Applying force to rigidbodies nearby (correct me if I'm wrong)
    27.         Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
    28.         foreach (Collider nearbyObject in colliders)
    29.         {
    30.             Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
    31.             if(rb != null)
    32.             {
    33.                 rb.AddExplosionForce(force, transform.position, radius);
    34.             }
    35.         }
    36.  
    37.  
    38. //And this is supposedly where the cloned particles would be destroyed
    39.  
    40.         //Destroying the cloned object (particles)
    41.         Destroy(GameObject.Find("Explosion(Clone)"), 1);
    42.     }
    43. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    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:

    Code (CSharp):
    1. GameObject explosionInstance = Instantiate(explosionEffect, transform.position, transform.rotation);
    2.  
    3. // other code here...
    4.  
    5. Destroy(explosionInstance, 1);
     
  3. ImprobableDoge

    ImprobableDoge

    Joined:
    Aug 4, 2021
    Posts:
    40
    Thank you so much!!!! It works completely fine now ;)