1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
John
  • 197
  • 1
  • 17

2 Answers2

2

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 );
    }
}
yasirkula
  • 591
  • 2
  • 8
  • 47
  • 1
    Why are you a genius? Seriously though thank you so much haha. I wasn't aware of Input.inputString but I tested it out and it's super helpful! Thank you!! – John Aug 08 '21 at 20:42
0

As far as I know, Unity doesn't have built-in KeyCode to char mappings.

I found a Gist that has a char to KeyCode dictionary. Simply swap the keys and values and you should be good to go: https://gist.github.com/b-cancel/c516990b8b304d47188a7fa8be9a1ad9

I don't want to put the code here in the answer since it is too long, but I made a fork in case the original Gist goes down: https://gist.github.com/starikcetin/62506e691ecd465159a235fb7acb44f0


Edit: Why don't you keep your cheat code in the form of a KeyCode array? Then you don't have to deal with chars.

starikcetin
  • 1,391
  • 1
  • 16
  • 24