Destroy function

Hello
I can’t call functions that both destroy the gameobject
in this script there are 2 functions with 2 different tags, one is for Playing animations and destroying invoking the void destroy after 1 second when colliding with a certain tag.
the other is Direct destroying of the object, no delay

the script:

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        animator.SetBool("HIT", true);
        Invoke("Dissapp", 1);
    }
if (collision.gameObject.CompareTag("ObsKill"))
    {
         Destroy(gameObject);
    }
}

public void Dissapp()
{
    Destroy(gameObject);
}
  1. I tried using different script, not working either
  2. both tags exist and assigned properly

the First method is the only one working and I tried everything

Can you provide a bit more detail about how it is not working?

  • Does it destroy the wrong object?
  • Does the code reach the line with the Destroy call?

It would be a good idea to add a Debug.Log() print just before each of the Destroy functions so that you know if the code is actually reaching that part.

By the way, gameObject is a reference to the GameObject that the script is attached to. You are correct that you don’t need to use this.gameObject.

it supposed to work on the any Object the Script attached to and it do work
for some reasons Destroy(this.gameObject); do not work

I used the method “SetActive(false)” and it work
although it’s super weird that this method work but destroy don’t
will that’s the end of this thread if you need any help

Well i’m assuming you’re making a 2D project, but if you’re not make sure you’re using the 3D version of the OnCollisionEnter function.

Make sure you’re properly configuring the “IsTrigger” option on both, maybe you do or don’t need it for the specfics of your game.

If everything is still not working, add a Debug.Log method inside of your invoke method, make sure that is firing first.

If it is, it might be something to do with your function, try a Coroutine instead:

void OnCollisionEnter2D(Collision2D collision)
{
     if (collision.gameObject.CompareTag(“Player”))
          {
               StartCoroutine(Dissapp());
          }

     if (collision.gameObject.CompareTag(“ObsKill”))
          {
                Destroy(gameObject);
          }
}

     IEnumerator Dissapp()
    {

        Debug.Log("Destroy");

        animator.SetBool(“HIT”, true);

        yield return new WaitForSeconds(1f);

        Destroy(gameObject);
    }
}

Also, make sure you’re not firing the destroy function of “ObsKill” by accident somewhere in the collision detection because it will destroy before it gets a chance to finish the coroutine or invoke method.

Destroy(gameObject) Only Destroy That GameObject Whom The Script Is Attached.
If You Want To Delete The Object Whose Tag Is Player Or ObsKill. Then You Need To Write Destroy(collision.gameObject) OR Destroy(collision.gameObject.CompareTag("tag")).