If statement inside OnControllerColliderHit() is calling twice of thrice sometimes

I have a running character in the game which have a character controller attached to it and I am using Move() method from Character controller to move player. I have different tag for different types of gameobjects to simulate player health, and I am destroying as soon as player colliding with any object and simulating the health according to object I collided. But I don’t know why, when colliding with some specific objects instead decreasing health by 20, my player health was reducing double, even triple. While I was getting the issue I added Debug.log(“Colliding”); to the code inside if statement to see what is going on inside OnControllerColliderHit(). And I found that “Colliding” was written in console twice or thrice at the same time without colliding with more than one objects. So I concluded that the if statement inside that OnControllerColliderHit() is called multiple times. I don’t know why is this happening…

Here is my code…

private void OnControllerColliderHit(ControllerColliderHit hit)
{

    if (hit.gameObject.tag == "Rock")
    {
        SpawnManager.DestroyObstacle(hit.gameObject);
        hitAudio.Play();
        if (health > 0f)
        {
            health -= 50f;
        }
    }
    if (hit.gameObject.tag == "Obstacle")
    {
        Destroy(hit.gameObject);
        hitAudio.Play(); 
        if (health > 0f)
        {
            Debug.Log("Collision");
            health -= 20f;
        }
    }

    HealthControl();
}

Hi!

Whenever you take damage you can try storing the gameobject that hit you. Then when checking for other collisions in that same frame, you know that you’ve already taken damage from that object and can skip the calculation.

Another perhaps better solution would be to just give your player some invincibility frames when they take damage. Most players will anyway expect some form of this upon getting hit.

Hope this helps!