0

I am trying to make a hangman game, but I don't quite know how to handle the input. I would like to have a string that I could then compare to the word the player is guessing.

if (Input.GetKeyDown(KeyCode.A))
{
  answer = "A"
}
else if (Input.GetKeyDown(KeyCode.B))
{
  answer = "B"
}

I know I could just repeat this 13 times but I was wondering if there is a better way of doing things.

silentw
  • 4,835
  • 4
  • 25
  • 45
Jan Hrubec
  • 59
  • 6

2 Answers2

2

I actually don't use Unity, but one option is to create Dictionary that maps key codes to strings. Then loop through that:

var codes = new Dictionary<KeyCode, string> {
    {KeyCode.A, "A"},
    {KeyCode.B, "B"},
    ....etc
};
...
foreach(var code in codes)
{
    if (Input.GetKeyDown(code.Key)) {
        answer = code.Value;
        break;
    }
}
001
  • 13,291
  • 5
  • 35
  • 66
2

Quoting my answer from another question:

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

private void Update()
{
    if( Input.anyKeyDown )
    {
        foreach( char c in Input.inputString )
            answer += char.ToUpperInvariant( c );
    }
}
yasirkula
  • 591
  • 2
  • 8
  • 47