- Home /
Get number input from user
Hello,
Super easy question. I am trying to make it so when the user presses a number between 0-9 it will multiply that number by 3. I don't know how to read in the numbers 0-9. The rest I can figure out.
Thanks in advance for anyones help!
Answer by Hellium · Dec 03, 2018 at 05:26 AM
private KeyCode[] keyCodes = new KeyCode []{ KeyCode.Alpha0, KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4, KeyCode.Alpha5, KeyCode.Alpha6, KeyCode.Alpha7, KeyCode.Alpha8, KeyCode.Alpha9 };
private void Update()
{
for( int i = 0 ; i < keyCodes.Length ; ++i )
{
if( Input.GetKeyDown( keyCodes[i] )
{
Debug.Log( i * 3 );
}
}
}
Otherwise, you can try the following, but I didn't tested it
private void Update()
{
int start
for( int i = (int) KeyCode.Alpha0 ; i < (int) KeyCode.Alpha9 ; ++i )
{
if( Input.GetKeyDown( (KeyCode) i )
{
Debug.Log( i - ((int) KeyCode.Alpha0 ) );
}
}
}
This is perfect! It does exactly what I need. I was thinking there was a way to code something like, between alpha0 and alpha9 without doing the array but I guess Unity is not there yet lol. Thank you for the response!
Answer by FoodLover195 · Dec 03, 2018 at 04:19 AM
Use this code as a basis for your script:
if (Input.GetKeyDown(KeyCode.Alpha1)) {
// Do Stuff
}
The if statement will run on the first frame the key is pressed. The function inside the if statement takes in a property KeyCode.Value. Have a look here for the other values:
Your answer
Follow this Question
Related Questions
Maths issue + Null reference error? -1 Answers
How can i make a number input look like that: 0 Answers
Simple Calculator for kid math app? 3 Answers