Home > OS >  OnTriggerEnter2D(Collider2D col) doesn't seem to be working
OnTriggerEnter2D(Collider2D col) doesn't seem to be working

Time:06-15

I've tried making this little thing where if the player clicks it shoots, but it doesn't seem to be working. Here is the code:


    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag != "player" || col.gameObject.tag != "fireball")
        {
            Debug.Log(col.gameObject.tag);
            Destroy(gameObject);
        }
    }

This code is meant to be if the col isn't equal to player or fireball it destroys the gameObject and debugs the col's tag.

But it destroys when it enters the player, and it also destroys when hitting the fireball. The fireball and it's children are called "fireball" and the player and children are called "player", it still destroys the fireball gameObject.

Any idea why this isn't working?

CodePudding user response:

Your if statement will always be true, as the tag will always be not "player" or not "fireball".

If you want it to not destroy if the tag is "player" or if the tag is "fireball", you will need to change your if statement to use && instead like so:

void OnTriggerEnter2D(Collider2D col)
{
    if (col.gameObject.tag != "player" && col.gameObject.tag != "fireball")
    {
        Debug.Log(col.gameObject.tag);
        Destroy(gameObject);
    }
}
  • Related