Multiple Input.GetKey

Hi,

I want a piece of code which says “if none of the following keys of pressed then…”

So this is what I think is most suitable. (I prefer Javascript).

if (!(Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))) {
// Then do what I want.
}

(I haven’t tried it yet but) it’s extremely long, and the length is quite annoying. Is there another way to do this, something like this:

if (!(Input.GetKey(KeyCode.UpArrow, Keycode.W //etc...

So how I could do this?

PS: This is different to if any key is pressed. Thanks!

Well, in C# you can create a function with a params parameter. This allows you to pass as much parameters as you like. I’m not sure if that’s possible in UnityScript.

This would work in C#

bool GetAnyKey(params KeyCode[] aKeys)
{
    foreach(var key in aKeys)
        if (Input.GetKey(key))
            return true;
    return false;
}

This function could be used like this:

if (GetAnyKey(KeyCode.UpArrow, Keycode.W /* , ... */ ))

Or for your case

if (!GetAnyKey(KeyCode.UpArrow, Keycode.W /* , ... */ ))

As general alternative you could define your keys in an array and pass the array to the function.

A few weeks into a regular bring programming class you’d see two ways to handle “none of the above”:

if(Input.GeyKeyDown("a")) {   .... }
else if(Input.GetKeyDown("b")) { ..... }
else if ...
else   // None of the above goes here

If you can’t organize things that neatly, the flag trick also works:

bool keyWasHandled=false;

if(Input.getKetDown("y")) { ... keyWasHandled=true; }
// everyone who processes a key should set: keyWasHandled=true

if(Input.AnyKeyDown && keyWasHandled==false) {
  // we have a key that no one else wanted
}

The array method (Bunny, above) is “better,” but only if you know arrays and, everyone else who’s going to mess with your code.

Here it is working :smiley: thanks for info guys. (very simple but it works all directions no sound cut off)

var AudioFile : AudioClip;

function Update() {

if ( Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ) )
{
     GetComponent.<AudioSource>().clip = AudioFile;
     GetComponent.<AudioSource>().Play();
}   
 
    else if ( !Input.GetButton( "Horizontal" ) && !Input.GetButton( "Vertical" ) && GetComponent.<AudioSource>().isPlaying )
{
     GetComponent.<AudioSource>().clip = AudioFile;
     GetComponent.<AudioSource>().Stop();
}

}

You could use input axes; by default, you have “Vertical” and “Horizontal” mapped to arrow keys and WASD, which gives you:

if (Mathf.Approximately(0.0f, Input.GetAxis("Horizontal") && Mathf.Approximately(0.0f, Input.GetAxis("Vertical"))
{
    // Then you do what you want
}

if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.RightArrow))