Comparing a variable (The right answer) to user input.
I simply display a number on the screen that you're supposed to press on your keypad. The available buttons are 0 to 3. What is a good way to see if the user's input (numbers on the keypad) is the same number as displayed on screen?
I started using a switch statement but that just got cluttered with identical if statements, it worked but there's got to be a more nicely packaged way of doing this.
The number I'm displaying on screen is contained as an int in a list. So I'm comparing an int to the equivalent number on the keypad (input).
(I suggest that only one input should be able to be true at ones to minimize the off chance of getting it right with button mashing.)
Answer by Downstream · Mar 25, 2016 at 10:05 PM
Here's a script for getting started.
using UnityEngine;
public class RayCaster : MonoBehaviour{
public int answer = 4;
int numstart;
public void Start(){
numstart = (int)KeyCode.Alpha0;
}
bool anyNumberPressed = false;
public void Update(){
for (int i = 0; i < 10; i++) {
if (Input.GetKeyDown ((KeyCode)numstart + i)) {
if (answer == i) {
Debug.Log ("YOU WIN");
anyNumberPressed = true;
} else {
Debug.Log ("YOU LOSE");
anyNumberPressed = true;
}
}
}
if (anyNumberPressed) {
answer = Random.Range (0, 9);
anyNumberPressed = false;
}
}
}
Oh wow. I didn't know you could so easily convert a variable's type like that! I have seen it done before, when instantiating gameObjects, but didn't realize I could use it in other contexts, this is truly an eye opener! I'm definitely gonna try to convert more types to open up more possibilities.
But to get to the point, this is exactly what I was talking about. I felt that repeating if statements was unnecessary and it turns out to be true. I also knew that I'd learn something from seeing another approach to the problem.
Answer by DThaiPome · Mar 25, 2016 at 10:01 PM
All you really have to do is store the user's input in a variable, then use an if statement to check if the input is the same as the correct answer.
To store an input, you can either use the Input.GetKeyDown function, or you can set up an axis in the inputs menu in the project, then use the Input.GetAxis function.