Search code examples
c#unity-game-enginegame-enginegame-development

How can I set a char variable to the KeyCode of Input.GetKey?


I'm trying to make a cheat code system. I had an array of chars. I want to assign whatever input the player puts in to that char, and then ill change the index to the next char and repeat with that. At the end I want to combine all the chars together to a string and see if that's a cheat code. If it is then the player will get a powerup or whatever.

I basically want the char to be whatever button I press. Is there any better way to do it that's not like this:

if (Input.GetKeyDown(KeyCode.A))
{
CodeAttempt[index] = 'a'
index++;
}
if (Input.GetKeyDown(KeyCode.C))
{
CodeAttempt[index] = 'b'
index++;
}
if (Input.GetKeyDown(KeyCode.C))
{
CodeAttempt[index] = 'c'
index++;
}

And so on?


Solution

  • You can use Input.anyKeyDown and Input.inputString (case-sensitive):

    private void Update()
    {
        if( Input.anyKeyDown )
        {
            foreach( char c in Input.inputString )
                CodeAttempt[index++] = char.ToLowerInvariant( c );
        }
    }