Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by tahir · Jan 12, 2015 at 10:12 PM · inputconsolebasicunity4.6basic programming

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

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image darthtelle · Jan 13, 2015 at 10:34 AM 0
Share

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.

avatar image tahir · Jan 13, 2015 at 12:47 PM 0
Share

@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.

avatar image alxsnchez · Jun 15, 2015 at 11:39 AM 0
Share
  1. 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.

  2. 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! :)

2 Replies

· Add your reply
  • Sort: 
avatar image
2

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image skauth · Feb 26, 2018 at 03:36 PM 0
Share

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.

avatar image
0

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();
     }
 }

}

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MarekNijaki · Apr 03, 2018 at 02:33 AM 0
Share

You can check how i did it (by coroutines)

Github/NumberWizard

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Cliks per second does not work 1 Answer

Quick question 1 Answer

Submit inputField when Enter is clicked 10 Answers

How Can I Create A Basic Developer Console? 0 Answers

Block all input while console is opened 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges