Disabling diagonal movement in Unity 5 2D? (using C#)

Or rather I should say, “EFFECTIVELY disabling diagonal movement”.

There are plenty of Q/As online about this, but I keep encountering the same problem: When moving horizontally (left, for example), I can override the current direction and start moving vertically (by pushing up), which is what I want. But it does not work the other way around! Vertical movement can not override horizontal movement.

void Update () {

         float h = Input.GetAxis("Horizontal");
         float v = Input.GetAxis("Vertical");
          ManageMovement(h, v); 
}    

void ManageMovement(float horizontal,float vertical) {

        if (vertical != 0f) {
                horizontal = 0f;
                Vector3 movement = new Vector3 (horizontal, vertical, 0);
                GetComponent<Rigidbody2D> ().velocity = movement * speed;
                return;
            } 

        if (horizontal != 0f) {
            vertical = 0f;
            Vector3 movement = new Vector3 (horizontal, vertical, 0);
            GetComponent<Rigidbody2D> ().velocity = movement * speed;
            return;

        } else {
            Vector3 noMovement = new Vector3 (0, 0, 0);
            GetComponent<Rigidbody2D> ().velocity = noMovement;
        }
    }

If I reverse the order of these if() statements, it reverses the problem. So, that’s a clue. But I’m not a great detective. I would love some help!

Part of the problem is that you’re looking for the direction component that’s not zero. Assuming you’re using a gamepad it’s likely that both directions will be non-zero. The way you have the code structured, the last if will always win. If you add an else before if (horizontal... then the first one that’s non-zero will always win.

What will probably work better is for you to compare the direction components against each other, so the bigger one wins.

if (h > v)
{
  // input is more horizontal than vertical so move horizontally
}
else if (v > h)
{
  // input is more vertical than horizontal so move vertically
}
else
{
  // don't move
}