Hi everone,
just want to write a script with
Input.GetKeyDown(KeyCode.Keypad0)
for all numbers 0-9 and then pass it to an “int”.
Just wondering if there is an easier way, (like accessing the KeyCode-ID) instead of writing a long if-case?
Hi everone,
just want to write a script with
Input.GetKeyDown(KeyCode.Keypad0)
for all numbers 0-9 and then pass it to an “int”.
Just wondering if there is an easier way, (like accessing the KeyCode-ID) instead of writing a long if-case?
Maybe this can help: c# - Receive any Keyboard input and use with Switch statement on Unity - Stack Overflow
Something like this?
Create a collection of all KeyCodes
that map to the respective 0-9 keyboard keys…
KeyCode[] keypadCodes = new KeyCode[]
{
Keypad0,
Keypad1,
Keypad2,
Keypad3,
Keypad4,
Keypad5,
Keypad6,
Keypad7,
Keypad8,
Keypad9
};
Write a function that checks if any of those KeyCodes
are down:
bool KeypadCodeDown(out KeyCode keypadCodeDown)
{
foreach(KeyCode keypadCode in keypadCodes)
{
if(Input.GetKeyDown(keypadCode))
{
// Output the KeyCode that was pressed.
keypadCodeDown = keypadCode;
return true;
}
}
// Output some default value to if none of the keypad codes were pressed.
keypadCodeDown = KeyCode.None;
return false;
}
Use that function when reading keypad inputs…
void Update()
{
if(KeypadCodeDown(out KeyCode keypadCode))
{
// A keypad code was pressed.
// The associated KeyCode value is outputted to the the "keypadCode" variable to do whatever with here.
}
}
Not exactly sure what you mean here. Do you simply want to cast the pressed KeyCode
to an int
like so?
void Update()
{
if(KeypadCodeDown(out KeyCode keypadCode))
{
int keyCodeAsInt = (int)keypadCode;
// Do something with keyCodeAsInt...
}
}
Or if you mean you want to get the actual keypad number associated with the KeyCode
that was pressed, you could use the index of the keypadCodes
array and modify the KeypadCodeDown
function like so:
bool KeypadCodeDown(out int keypadNumber)
{
for(int i = 0; i < keypadCodes.Length; i++)
{
if(Input.GetKeyDown(keypadCodes[i])
{
// Output the keypad number that was pressed.
keypadNumber = i;
return true;
}
}
// Output some default value to if none of the keypad codes were pressed.
keypadNumber = -1
return false;
}
Since input arrives at any application as events with a particular scan code which is then translated into a KeyCode, the easiest solution is to use OnGUI and the Event class. It provides direct access to most relevant input events. Of course OnGUI is aimed at UI design, but such trivial things can be detected just fine:
void OnGUI()
{
Event e = Event.current;
if (e.type == EventType,KeyDown)
{
int k = (int)(e.keyCode - KeyCode.Keypad0));
if (k >= 0 && k <= 9)
{
Debug.Log("pressed num pad key " + k);
// Do something here
}
}
}