Home > Enterprise >  why does 'if' and 'else' both get executed in Unity?
why does 'if' and 'else' both get executed in Unity?

Time:10-24

I'm trying to detect collision in some cases, headshot, not headshot, missing the target. Here is how I tried to achieve it:

  private void OnCollisionEnter(Collision collision)
    {
        if (interations.won && interations.currentlyPickedUpObject == null)
        {
           
            if (collision.collider == head) 
            {
                Debug.Log("HeadShot");
            }
            if (collision.collider == body || collision.collider == feet)
            {
                Debug.Log("Not a HeadShot");
            }
            else 
            {
                 Debug.Log("You've missed the target");
            }
        }
    } 

The issue I'm facing is that the if and the else both get executed! shouldn't the else block get executed only if the if conditions are not met? why is this happening? I want to execute the else part only if the two conditions are false!

enter image description here

CodePudding user response:

Try to change the second if with else if, like this

else if (collision.collider == body || collision.collider == feet)

In your code, the else condition is linked only with the second if condition, and not the first if.

CodePudding user response:

They are both executed, because you got two if statements. Your first if statement is separate from the else, which in turn is tied to the second if.

Imagine collider is a head: your first if will be true. Then you go to the second if - the collider is neither body nor feet, and you go to the else, hence your code logs both HeadShot, and You've missed the target

To prevent that, you can use else if:

if (collision.collider == head) 
{
    Debug.Log("HeadShot");
}
else if (collision.collider == body || collision.collider == feet)
{
    Debug.Log("Not a HeadShot");
}
else 
{
     Debug.Log("You've missed the target");
}

as it will prevent the code from choosing multiple options.

  • Related