Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reference the "SpaceBar" Key in C# (Unity)?

In Unity, how do I reference the SpaceBar Key in order to apply force to an object when Space Bar is pressed?

void Update()
{
    rb.AddForce(0, 0, forwardforce * Time.deltaTime);

    if (Input.GetKey("a"))
    {
        rb.AddForce(500 * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("w"))
    {
        rb.AddForce(0, 0, -500 * Time.deltaTime);
    }
    if (Input.GetKey("s"))
    {
        rb.AddForce(0, 0, 500 * Time.deltaTime);
    }
    if (Input.GetKey("d"))
    {
        rb.AddForce(-500 * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("vbKeySpace"))
    {
        rb.AddForce(0, 300 * Time.deltaTime, 0);
    }
}
like image 375
Ethan Elmore Avatar asked Dec 05 '25 14:12

Ethan Elmore


2 Answers

You could try the following:

Input.GetKey("space");

Or, using the KeyCode enumeration:

Input.GetKey(KeyCode.Space);

See the docs on this enumeration here.

like image 135
Sigge Avatar answered Dec 08 '25 04:12

Sigge


Input.GetKey operates on the string-names of the Conventional Game Input key list.

Special keys: “backspace”, “tab”, “return”, “escape”, “space”, “delete”, “enter”, “insert”, “home”, “end”, “page up”, “page down”

However, I recommend looking into Input.GetButton instead. This allows the player to rebind the keys to something more suitable for them, rather than being forced to use WASD and Space.

So you would instead use Input.GetButton("Jump") and define in Edit -> Project Settings -> Input that "Jump" is mapped to the positive key "space" (Unity will auto-supply some default keys, and Jump:Space is one).

Additionally you can switch your Input.GetKey("a")/Input.GetKey("d") with Input.GetAxis("Horizontal").

like image 36
Draco18s no longer trusts SE Avatar answered Dec 08 '25 03:12

Draco18s no longer trusts SE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!