Converting string of a key into KeyCode

Hi Everyone !

I’ve been browsing the web for around 2 days now about my problem.

I’m trying to convert a string (like “0”, or “#”) into a Keycode.

I have a number of key written in my scene, and I want to automatically check if they are pressed (for example if there is a “#” written, the code will go through the string of this (“#”) and check each frame if this particular key is pressed).

I have found some solution but they didn’t work (for example the code was trying to compare “Keypad0” to “0” so obviously it didn’t match).

Anyone has an idea ?

Something like this might work since the enum keycode uses the numbers of each char.

I also cached it here to prevent unnecessary enum parse calls.

private readonly Dictionary<char, KeyCode> _keycodeCache = new Dictionary<char, KeyCode>();

private KeyCode GetKeyCode(char character)
{
    // Get from cache if it was taken before to prevent unnecessary enum parse
    KeyCode code;
    if (_keycodeCache.TryGetValue(character, out code)) return code;

    // Cast to it's integer value
    int alphaValue = character;
    code = (KeyCode)Enum.Parse(typeof(KeyCode), alphaValue.ToString());
    _keycodeCache.Add(character, code);
    return code;
}

you can compare it like this

Debug.Log(KeyCode.B.ToString().Equals("B"));