I am implementing a virtual console for my game and I am piping Key up events thro an event pipe (Observable Subject) and handling them on the virtual console side with
public void ReceiveInput (Event e)
{
Debug.Log ("ReceiveInput: " + e.ToString ());
if (e.keyCode == KeyCode.Backspace) {
if (ConsoleInputLine.LineText.Length > 2)
ConsoleInputLine.RemoveLastChar ();
return;
}
if (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter) {
ConsoleInputLine.LineText = "$ ";
return;
}
var chr = e.keyCode.ToString ();
if (e.capsLock || e.shift)
chr = chr.ToUpper ();
else
chr = chr.ToLower ();
ConsoleInputLine.AppendText ("" + chr);
}
While this works for simple A-Z and a-z letters, when you get to the numbers and other characters I will get the raw key name, such as "Alpha1" for the horizontal "1" key above the "Q" key, "Alpha2" for the "2" above "W", etc.
Is there a way to easily get the "rendered" text out of the key events without building a switch of all the possible keycode results?
PS: I forgot to mention that, shift+Alpha1 is "!" in US Querty, shift+Alpha2 is "@", etc, but it will differ in keyboards of different countries and its not feasible to make switch statements for every keyboard in the world.
This is not the correct answer!!!
Leaving it here in the spirit of assisting further research or get someone out of a jam.
For US Querty only keyboards, this works for now, until someone replies with a proper answer :
public static char ToChar (this Event e)
{
var key = e.keyCode;
char c = '\0';
if ((key >= KeyCode.A) && (key <= KeyCode.Z))
return (char)((int)((e.shift || e.capsLock) ? 'A' : 'a') + (int)(key - KeyCode.A));
if ((key >= KeyCode.Alpha0) && (key <= KeyCode.Alpha9)) {
if (e.shift) {
var specials = new char[] {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'};
return specials [(int)(key - KeyCode.Alpha0)];
}
return (char)((int)'0' + (int)(key - KeyCode.Alpha0));
}
if (key == KeyCode.Space)
return ' ';
if (key == KeyCode.Quote)
return (e.shift) ? '"' : '\'';
if (key == KeyCode.LeftBracket)
return (e.shift) ? '{' : '[';
if (key == KeyCode.RightBracket)
return (e.shift) ? '}' : ']';
if (key == KeyCode.BackQuote)
return (e.shift) ? '~' : '`';
if (key == KeyCode.Backslash)
return (e.shift) ? '|' : '\\';
if (key == KeyCode.Equals)
return (e.shift) ? '+' : '=';
if (key == KeyCode.Minus)
return (e.shift) ? '_' : '-';
if (key == KeyCode.Semicolon)
return (e.shift) ? ':' : ';';
if (key == KeyCode.Comma)
return (e.shift) ? '<' : ',';
if (key == KeyCode.Period)
return (e.shift) ? '>' : '.';
if (key == KeyCode.Slash)
return (e.shift) ? '?' : '/';
// implement more
return c;
}