Home > database >  How to read keys that user presses without specifying the exact key?
How to read keys that user presses without specifying the exact key?

Time:05-03

Basically what I need is an idea how to shorten my code.

So what I have now is an IF series to get the keys that user presses:

if (Input.GetKeyDown(KeyCode.I))
        {
            AddToBuffer("I");
        }
        else if (Input.GetKeyDown(KeyCode.N))
        {
            AddToBuffer("N");
        }
        else if (Input.GetKeyDown(KeyCode.F))
        {
            AddToBuffer("F");
        }

It works perfectly well, but what I want is to shorten it so it would be possible to save to buffer any key (better, as a string)

So that I would no more have to specify what key was pressed.

(Maybe something like TryParse etc.)

CodePudding user response:

InputString contains a string all keys pressed down on the current frame. It is recommended to break the string down into characters as shown in the input string example in Unity documentation, as inputString can contain backspace '\b' and enter '\n' characters.

An example of listening for cheatcodes might look like this:

string cheatCode = "money";
int cheatIndex = 0;
void Update()
{
    if(Input.anyKeyDown)
    {
        foreach (char c in Input.inputString)
        {
            if(c == cheatCode[cheatIndex])
            {
                //the next character was entered correctly
                Debug.Log("The next character {0} was entered correctly", c);
                //On the next key down, check the next character
                cheatIndex  ;
            } else
            {
                //The character was not correctly entered, reset the cheat index back to the start of the code
                Debug.Log("Cheat code invalid. {0} was not the next character", c);
                cheatIndex = 0;
            }
        }
        if(cheatIndex == cheatCode.Length)
        {
            Debug.Log("Cheat code was successfully entered")
        }
    }
}

I have not written this in Unity and tested it, so your mileage may vary.

CodePudding user response:

You can use "any key": https://docs.unity3d.com/ScriptReference/Input-anyKey.html

if (Input.anyKey)
{
    Debug.Log("A key or mouse click has been detected");
    // get the pressed key:
    String keycode = Event.current.keyCode.ToString();
}
  • Related