Unity freeze when running a very basic script

Hello,
I just started learning Unity/C# but I’m having a problem with one of my first scripts. When I try to run this script it Unity freeze and I have to close it using the Task Manager.
This is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class NumberWizard : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int min = 1, max = 100;
        Debug.Log("Hello and welcome to Number Wizard");
        Debug.Log("Please choose a number between 1 and 100");
        Debug.Log("Let me guess your number...");
        GameWizard(min, max);
    }

    static void GameWizard(int min, int max)
    {
        Debug.Log("Your number is " + GuessNumber(min, max));
        Debug.Log("Is it correct? Tell me if it is (C)orrect, too (B)ig or too (S)mall");
        string userInput = Console.ReadLine().ToLower();
        switch (userInput)
        {
            case "c":
                Debug.Log("I was right! Nice :)");
                return;
            case "b":
                Debug.Log("Retrying...");
                GameWizard(min, GuessNumber(min, max));
                return;
            case "s":
                Debug.Log("Retrying...");
                GameWizard(GuessNumber(min, max), max);
                return;
        }
    }

    static int GuessNumber(int min, int max) => (min + max) / 2;

    // Update is called once per frame
    void Update()
    {
       
    }
}

I tried to use this code for a Console App and it works as expected, I can’t figure out what the problem is.

Thank you in advance.

Oh neat. I learned something from this question. I had not thought to call into the System.Console from within unity. You can’t do that.

The short answer is that you can’t use the System.Console.ReadLine() method. You should use one of Unity’s ways of getting user input. Unity’s static Input class is probably the easiest to use right now.

As the simplest way, I suggest putting your switch case into the Update method:

if (Input.GetKeyDown(KeyCode.C)) {
    Debug.Log("I was right! Nice :)");
    return;
}
else if (Input.GetKeyDown(KeyCode.B)) {
   // do the "b" case here
}
else if (Input.GetKeyDown(KeyCode.S)) {
    // do "s" case
}

and so on

1 Like

if user input is not equal to c you’ll be stuck in a recusive loop, I’m pretty sure new input won’t be recived unless you use a coroutine and wait a frame…

also, how does console.readline work in unity…?

It doesn’t.

2 Likes

thought so, lol.

Thank you

Now I’m curious about trying Console.ReadLine() from a headless build lol

But to the OP, you probably want to use an inputfield and a button to say when done. It is also possible to capture the enter key in place of a submit button, but that is more complicated than you’d think (though there are threads with code examples on doing so).