I’m currently reading Input.inputString and then calling int.TryParse on it to see if it’s a number that was pressed, so that I can switch the weapon depending on which number was pressed.
And it works fine when I press the numbers by themselves on the keyboard, but when I’m pressing shift and then press a number, I get the alt-character of that key in the Input.inputString instead of the number that was pressed.
So for example, pressing SHIFT + 2 returns “@” and when pressing SHIFT + 3 returns “#” etc…
Is there a way on how I can get the number that was pressed without Input.inputString converting the characters?
Is there any reason for why you’re not doing Input.GetKeyDown(KeyCode.Alpha1 - KeyCode.Alpha9)? That gets you out of the shift problem, and saves you on the string parse operation.
I suggest you use Input.GetKey, Input.GetKeyDown, Input.GetKeyUp for what it is you are doing. Anything else like using the Events is pretty weird…Since you are waiting for two operations IE two button states you can’t sue Input.GetButton(“Swap Secondary”) or something as it only listens to one input at a time.
So what you want to do is listen for the Shift or some other predefined key. If that shift is being pressed check if they have pressed a weapon swap key that is also predefined.
KeyCode m_weaponQuickShift = KeyCode.LeftShift;
KeyCode m_primary = KeyCode.Alpha1;
KeyCode m_seconary = KeyCode.Alpha2;
// ...etc
// Check if the user is pressing the weapon quick shift key
if(UnityEngine.Input.GetKey(m_weaponQuickShift)) {
// If so...
// Check if they are trying to swap the primary
if(UnityEngine.Input.GetKeyDown(m_primary)) {
// Seems like they want to swap the primary
} else if(UnityEngine.Input.GetKeyDown(m_seconary)) {
// Seems like they want to swap the secondary
}
}
public bool GetKeyboardNumberPressed(out int number)
{
// TODO: I've yet to profile whether it would be better to add a Input.anyKeyDown check here
number = -1;
for (var i = 0; i <= 9; ++i)
{
if (Input.GetKeyDown(ConvertNumberToKeycode(i)))
{
number = i;
return true;
}
}
return false;
}
private KeyCode ConvertNumberToKeycode(int number)
{
switch (number)
{
case 0: return KeyCode.Alpha0;
case 1: return KeyCode.Alpha1;
case 2: return KeyCode.Alpha2;
case 3: return KeyCode.Alpha3;
case 4: return KeyCode.Alpha4;
case 5: return KeyCode.Alpha5;
case 6: return KeyCode.Alpha6;
case 7: return KeyCode.Alpha7;
case 8: return KeyCode.Alpha8;
case 9: return KeyCode.Alpha9;
}
return KeyCode.None;
}