OnTriggerEnter2D called twice sometimes when IsTrigger is ON

I have a game object with only a box collider 2d (IsTrigger is ON) attached to it. I use this to detect ( using OnTriggerEnter2D() ) when player falls on it so that the life count is reduced by 1. But most of the times, it is called twice and life count decrements by 2. After a lot of debugging I found out that this issue only happens when IsTrigger is ON. It doesn’t happen when IsTrigger is OFF. Why is it happening? Is there a problem in my code or is it some sort of unity error?

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Deadly")
        {
            lifeCount = lifeCount - 1;
            player.SetActive(false);

            if (lifeCount <= 0)
            {
                DiedPanel.SetActive(true);
            }
            else
            {
               //Some code here to reposition player
               //It is made sure that the player is not positioned on the Deadly.
                player.SetActive(true);
            }
        }
  }

Hi, Is it the only "OnTriggerEnter2D" function you have in your project? I'm sure it's not a Unity issue. This function is probably called twice when on trigger enter. So you have this GameObject with Trigger Collider and your Player? Could you give your Player hierarchy or collider?

ONE MORE THING TO MENTION HERE: It also double counts the collisions between player and collectables. So when I pick up the coin (with a Circle Collider 2D), it increases the coinCount by 2 (not always but usually). Setting IsTrigger to false solves the problem in this case as well.

2 Answers

2

So, here is the solution (finally):
I had isTrigger ON on both objects that were colliding. So both of their OnTriggerEnter2D was activated. Although, I have had attached the script on only the player, their was a double decrement. In short:
Do not set both objects’ IsTrigger to TRUE

I need them to spawn in waves etc 1 enemy 1 enemy 2 enemy 3 enemy etc

I think it’s because you’re using “player.SetActive()”. Your Player is active, so Trigger is called, next you’re using player.SetActive(false), so GameObject is deactivated and not in collision with your Collider, and “if lifeCount > 0” you’re using SetActive(true), so Player is activated and enters again in collision, OnTriggerEnter is called.

No. Actually, I reposition the player before resetting SetActive to true.