2

I don't want to use if statement. For simplicity and performance I want to use switch case and execute that method. I want all the keyboard Input to get detected. But is there any method that will pass any key press information? My current approach is :

// Update is called once per frame
void Update()
{
    char a = Input.GetKey();//anything like this method?
    switch (a)
    {
        case 'a':
                //print'';
                break;
        case 'b':
                //print'';
                break;
        default:
            break;
    }

}

How can I achieve this any key press information detection without if statement?

4
  • Is you current approach not working? Commented May 30, 2019 at 7:29
  • no. Input.GetKey(); is not valid. Commented May 30, 2019 at 7:30
  • Right, sorry, I get the question now. Commented May 30, 2019 at 7:30
  • A single switch on key letters can't handle a situation where multiple keys are pressed or released in a frame. It's unclear what exactly you'd want from an answer, since your comments on the answers indicate you don't want to use a loop. Commented May 30, 2019 at 8:00

3 Answers 3

3
foreach(KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
{
    if (Input.GetKey(kcode))
    Debug.Log("KeyCode down: " + kcode);
}

Also you can cache the value of Enum.GetValues(typeof(KeyCode)) for optimization.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for this working solution, However this registers multiple events on single key press as it triggers on each frame so have to filter with keydown and keyup functionality.
@Rifat You may only care about few keys such as WASD, so we can put them to a list, just check these specific keys, which will not consume much CPU times and GC.
2

Best Solution - Use Input.inputString

You may use Input.inputString to catch the keyboard input entered in the last frame as a string.

void Update()
{
    //get the input
    var input = Input.inputString;
    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
        //logic related to the char pressed
        Debug.Log("Pressed char: " + Input.inputString);
}

Other solutions

Foreach Loop

You might use foreach loop approach, like suggested in other answers, but it is not as performant. Foreach allocates more memory and must check against all possible keys (it is also less readable).

If you do not care about time and memory performance, then you might follow this answer. It uses the foreach loop approach and create a reusable interface.


OnGUI

Finally you could catch the Event.current (that is a unityGUI Event), like explained in this answer, but doing so you would rely on the OnGUI method. This method has the worst performance.

11 Comments

Input.inputString is a working solution. Given example of thisEvent.keyCode doesn't work, requires a reference. Can you please mention how to catch charecter with - char c = Event.keyCode; manner instead of using foreach loop? Thanks.
If you strictly want to use char I would go with Input.inputString. I've never converted keycodes to chars. You can find an helper here, but it's just a dictionary that relates chars to keycodes.
I wanted to mark this as accepted since it was first to make a solution but your Event.keyCode example is incorrect, gives "NullReferenceException: Object reference not set to an instance of an object" error, and was not modified after first comment.
Sorry, I misunderstood the comment then. Have you set the EventSystem in the scene?
Yes there is a event system, and my scene has multiple buttons.
|
2

I've not used Unity, however, I understand your problem and I am a C# developer.

From a quick search I have found someone on Unity forums with a similar problem to you. Here is the thread https://answers.unity.com/questions/1520939/check-if-there-is-a-keyboard-input.html.

if (Input.anyKeyDown)
 {
     Event e = Event.current;
     if (e.isKey)
     {
         Debug.Log("Current Key is : " + e.keyCode.ToString());
     }
 }

The code above (from the Unity forum link) enables you to detect input.anyKeyDown (keyboard and mouse). Then you can filter the mouse detections by checking if the input was only a keyboard input with e.isKey

Here is documentation for KeyCode. This also includes all the properties available to it (many keyboard related properties that you can potential check against).

For example (not tested):

Event e = Event.current;
if (e.isKey)
{
    Debug.Log("Current Key is : " + e.keyCode.ToString());

    if(e.keyCode == KeyCode.A) //checks if the keycode returned equals the 'A' key
    {
         // Do something
    }
}

EDIT: As mentioned by the other answer you can try Input.inputString. According to the documentation insputString contains "Only ASCII characters". So for example you could do something like this in the 'Update' method if letters was what you were only looking to check.

void Update()
{
    //get the input
    var input = Input.inputString;

    //ignore null input to avoid unnecessary computation
    if (!string.IsNullOrEmpty(input))
    {
        switch(input)
        {
            case 'a': break;
            case 'b': break;
        }
    }
}

Hope this can help.

2 Comments

The Event.current is not working in the Update method, but only in the OnGUI method, so I think is not usable for this use case.
My bad I didn't know about that. Maybe with the updated logic in the Update method might help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.