Why does writing an if statemen one way works, but writing it another way doesn't?

Why does this work:

        if(Input.GetKey(KeyCode.LeftArrow))
        {
            if(state.HasFlag(PlayerState.Grounded))
            {
                state |= PlayerState.FacingLeft;

                spx = -0.1f;
            }
        }

But this doesn’t:

        if(Input.GetKey(KeyCode.LeftArrow) && state.HasFlag(PlayerState.Grounded))
        {
            state |= PlayerState.FacingLeft;

            spx = -0.1f;
        }

Aren’t these technically the same thing? I have never encountered this issue before where I have to split the if statement checks into separate if statements.

Those should be logically equivalent. Can you explain what you mean by the second one not working? I suspect something else is the cause of any behavior difference you’re seeing.

1 Like

You can replace “should” with “are” :slight_smile: They are literally the same. There may be a difference if there are other things involved like an “else” / “else if” behind one of these statements. Of course they would behave differently. However as the code is presented, they are 100% the same and work the same. This is something I don’t even need to test, this is a given fact.

So if you really see different results, there has to be something else involved.

As two folks above noted, it’s equivalent. I bet if you stuck a Debug.Log() in beside the flag-set you’d find them both firing, and then later you’d find some other thing that is clearing your faceleft flag and it happened to synchronize with your test.

Code is like that. Trust nothing. When something works, try to make it fail. If you can’t make it fail then you probably didn’t make it work either. :slight_smile:

1 Like