- Home /
Printing text to Console & Getting User Input
Hi,
I'm just starting up Unity & I'm new to programming. Enrolled for Udemy course Learn To Code by Making Games & I'm just through first two sections.
I'm trying to create a basic console based game where AI have to guess the number within a desired range.
I want to implement user selection where He/She will be able to select from predefined ranges and the search will be performed within that range. Here is the code I have:
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int max;
int min;
int guess;
// Use this for initialization
void Start () {
StartGame();
}
void StartGame () {
min = 1;
guess = 500;
print ("============================================");
print ("Welcome to the number Wizard, Where I'll guess the Number within a few Itterations!!");
print ("Please Select the Range in which you want your number to be, select the corresponding number!!");
print ("============================================");
print ("1 - 100 - Press 1");
print ("--");
print ("1 - 1000 - Press 2");
print ("");
print ("1 - 10000 - Press 3");
print ("--");
print ("1 - 100000 - Press 4");
print ("--");
print ("============================================");
print ("Please Input your desired range number?");
UserInput();
}
void NextGuess () {
guess = (max + min)/2;
print ("Heigher or Lower than " + guess + "?");
print ("Up Arrow = Higher, Down = Lower, Return = Equal");
}
void UserInput () {
if ((Input.GetKeyDown (KeyCode.Keypad1))||(Input.GetKeyDown (KeyCode.Alpha1))){
print ("You've Selected the Range from 1 - 100 :");
max = 100 + 1;
NextGuess();
} else if ((Input.GetKeyDown (KeyCode.Keypad2))||(Input.GetKeyDown (KeyCode.Alpha2))){
print ("You've Selected the Range from 1 - 1000 :");
max = 1000 + 1;
NextGuess();
} else if ((Input.GetKeyDown (KeyCode.Keypad3))||(Input.GetKeyDown (KeyCode.Alpha3))){
print ("You've Selected the Range from 1 - 10000 :");
max = 10000;
} else if ((Input.GetKeyDown (KeyCode.Keypad4))||(Input.GetKeyDown (KeyCode.Alpha4))){
print ("You've Selected the Range from 1 - 100000 :");
max = 100000 + 1;
NextGuess();
} else {
print ("Sorry, couldn't find your Range, Please Select Again!!");
Start();
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow)){
print ("Up Arrow key was pressed");
min = guess;
NextGuess();
} else if (Input.GetKeyDown (KeyCode.DownArrow)){
print ("Down Arrow key was pressed");
max = guess;
NextGuess();
} else if (Input.GetKeyDown (KeyCode.Return)){
print ("Hahaaa.....I Won!!");
StartGame();
}
}
}
Unity stops responding when I run this code, some kind of infinite loop is happening around, not sure of what it is.
Can you please take a look at the code and help me out in here.
Thanks,
Tahir
When you run this code, does it instantly stop working? Or when you press a button? Try setting some breakpoints in $$anonymous$$ono to pinpoint whether it's crashing in the Start() or the Update() function.
@darthtelle Thanks a lot. Well, I couldn't see anything happen around, Unity just stops responding & I have no other choice but to close it from the task manager.
UserInput() is only called once at the beginning of the "game". So there's no material time for the user to enter the selection before the programa automatically detect "0" as an option. UserInput() should be into the Update() function, so it's checked every frame until the user press a key.
As I told you, Start() function only called once in ALL entire game, so you shouldn't called again from the UserInput() method. You can do the same effect just by calling StartGame(), the method you have inside Start() and should be fine.
Hope it help! :)
Answer by Ambro · Jan 13, 2015 at 01:29 PM
I think you are freezing Unity by recursively calling your Start function.
Your Start function does this :
1 - Call StartGame and do a bunch of print then call UserInput
2 - Userinput should retrieve some user input, but I'm pretty sure that you can't do that before the Start function has finished (your object is not properly iniliatized). So it jumps directly to the last "else" section which call Start again. <- Here is your infinite loop !
User input should be retrieved in Update function.
Absolutely right about the recursion. I know this is a bit of a necro comment, but there's a big misconception that the asker has, and I want to put this out there for those who come across the same misconception:
Unity does not wait for user input. Unity checks for user input on the most recent tick (update).
So UserInput is implemented wrong, in addition to calling the method that called it (recursion), because the structure is based on a wait-for-the-next-keystroke kind of model. But all the if statements look at Just the most recent update. A better approach would be have multiple stages (Selecting Range, Guessing, etc). And in your Update method, call the appropriate stage update method (RangeSelectUpdate), which would go through the list and if you pressed one of the right keys, move to the next stage. And if not, it would not do anything.
If you did want to wait for input, UserInput would have to return an IEnumerator, I do believe (ins$$anonymous$$d of void). Which allows you to yield each update until the condition of your if statement has been met. You would call it using StartCoroutine(UserInput());
I have not yet found away to check for any key down, only specific keys.
Answer by dnaloco · Apr 01, 2018 at 12:13 AM
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class NumberWizard : MonoBehaviour { public int min, max, guess;
public bool resetGame = false, iWon = false;
public static string
msgWelcome = "Welcome to Number Wizard",
msgPick = "Pick a number in your head, but don't tell me!",
msgInfo1 = "The highest number you can pick is {0}",
msgInfo2 = "The lowest number you can pick is {0}",
msgInstructions = @"UP ARROW => for higher;
DOWN ARROW => for lower & RETURN(enter) => for equal.", msgGuess = "Is the number higher or lower than {0}?";
public static string[] msgRanges = new string[4] {
"1 - 100 - Press 1",
"2 - 1000 - Press 2",
"3 - 10000- Press 3",
"4 - 100000 - Press 4"
};
// Use this for initialization
void Start () {
SetInitialValues(1000);
InitialInstructions();
}
void InitialInstructions()
{
print(msgWelcome);
print(msgPick);
print(string.Format(msgInfo1, max));
print(string.Format(msgInfo2, min));
print(msgInstructions);
print(string.Format(msgGuess, guess));
max = max + 1;
}
void ChoosedRange()
{
print("============================================");
print("Want to try a new range?");
foreach (string r in msgRanges)
{
print(r);
print("----");
}
print("============================================");
print("Please Input your desired range number?");
if ((Input.GetKeyDown(KeyCode.Keypad1)) || (Input.GetKeyDown(KeyCode.Alpha1)))
{
resetGame = true;
print("You've Selected the Range from 1 - 100 :");
SetInitialValues(100);
InitialInstructions();
}
else if ((Input.GetKeyDown(KeyCode.Keypad2)) || (Input.GetKeyDown(KeyCode.Alpha2)))
{
resetGame = true;
print("You've Selected the Range from 1 - 1000 :");
SetInitialValues(1000);
InitialInstructions();
}
else if ((Input.GetKeyDown(KeyCode.Keypad3)) || (Input.GetKeyDown(KeyCode.Alpha3)))
{
resetGame = true;
print("You've Selected the Range from 1 - 10000 :");
SetInitialValues(10000);
InitialInstructions();
}
else if ((Input.GetKeyDown(KeyCode.Keypad4)) || (Input.GetKeyDown(KeyCode.Alpha4)))
{
resetGame = true;
print("You've Selected the Range from 1 - 100000 :");
SetInitialValues(100000);
InitialInstructions();
}
}
void SetInitialValues(int _max)
{
resetGame = false;
iWon = false;
min = 1;
max = _max;
guess = (max+1)/2;
}
void NextGuess()
{
guess = (min + max) / 2;
print(msgInstructions);
print(string.Format(msgGuess, guess));
}
// Update is called once per frame
void Update() {
if (Input.GetKeyDown(KeyCode.UpArrow))
{
min = guess;
NextGuess();
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
max = guess;
NextGuess();
} else if (Input.GetKeyDown(KeyCode.Return) )
{
print("I WON!!!");
iWon = true;
}
else if (iWon && !resetGame)
{
ChoosedRange();
}
}
}
You can check how i did it (by coroutines)
Your answer
Follow this Question
Related Questions
Cliks per second does not work 1 Answer
Quick question 1 Answer
Submit inputField when Enter is clicked 10 Answers