When a selected key is pressed in Unity, the Input Manager's Input.GetAxis("Horizontal") function returns a gradually increasing number up to 1 (or negatively -1) for the length it is held down. The rate at which it increases is based on the value Sensitivity in the Input Manager. Similarly, the sticks on a controller return a value depending on how far they are tilted.

Is there a proper way to make the value immediately snap to -1 or 1 through the manager, or would I have to write a couple of if statements in my script to handle that?\

Edit: A very short and readable scripting option would be if (Mathf.Abs(isRunning) > 0) isRunning = Mathf.Sign(isRunning);

  • 1
    \$\begingroup\$ Something wrong with if(value < 0) {...} else if (value > 0){...}? \$\endgroup\$
    – House
    Jun 1 '15 at 5:28
  • 1
    \$\begingroup\$ You could just cast the return value to an int. Thus you'll get -1 or 1 once the appropriate button is pressed. For more precision you could take a look at Math.Round. \$\endgroup\$
    – Kagemusha
    Jun 1 '15 at 5:29
  • \$\begingroup\$ This is more for curiosity, it seems crazy that this option isn't available in the manager \$\endgroup\$ Jun 1 '15 at 6:13
  • 1
    \$\begingroup\$ If you're using a keyboard, What's wrong with Input.GetAxisRaw("Horizontal");? docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html \$\endgroup\$
    – Savlon
    Jun 2 '15 at 13:10
  • \$\begingroup\$ Yes, that's what I'm looking for @Savlon. I think that should be the accepted answer if you would convert it to one. \$\endgroup\$ Jun 3 '15 at 16:06

Reference: http://docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html

If you are wanting the value to be -1, 0 or 1, use GetAxisRaw for keyboard inputs.


I think you would need to do it the if statement way.

For instance...

For the value to be either 1 or -1:

int amount = Input.GetAxis("Horizontal") > 0 ? 1 : -1;

For the value to be 1, 0, or -1:

float f;
int amount = (f=Input.GetAxis("Horizontal")) > 0 ? 1 : f < 0 ? -1 : 0;
  • 1
    \$\begingroup\$ The first statement is a bad idea since it's never zero. Zero indicates no key is pressed. The second statement is overly complicated as a one-liner, and would be easier to break out into multiple statements (in my opinion). \$\endgroup\$
    – House
    Jun 1 '15 at 5:40
  • \$\begingroup\$ Good points, I don't disagree. \$\endgroup\$ Jun 1 '15 at 5:43
  • \$\begingroup\$ That's too bad, I'm really disappointed there isn't such a trivial setting available \$\endgroup\$ Jun 1 '15 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.