- Home /
Blocking and retrieving user keyboard input
I'm implementing my own version of a command line interface/terminal, but I'm struggling with how I would block/wait for user input. My gut tells me I should be trying to emulate something along the lines of .NET's Console.Read(), which returns a string with the user's input.
I've got a solution that works in what feels like a really round-about way. I'm using coroutines to wait for user input, and when return is pressed, I set a private variable with the user input, and then access it after I call my Read() coroutine. It works, but it just feels messy. I'm trying to figure out if this is a reasonably acceptable way of doing things.
Here's the gist of what I'm doing
private string input;
private string keyboardInput;
private bool returnPressed = false;
void Start ()
{
//initialize stuff
StartCoroutine(StartGame());
}
void Update()
{
//Capture keyboard input (abbreviated for clarity)
keyboardInput += Input.inputString;
}
private IEnumerator StartGame()
{
WriteSomeText("Enter a value: ");
yield return StartCoroutine(Read());
string userInput = input;
//Do stuff
WriteSomeText("Enter another value: ");
yield return StartCoroutine(Read());
string userInput = input;
//Do more stuff
}
private IEnumerator Read()
{
input = "";
keyboardInput = "";
while(!returnPressed)
{
if(Input.GetKeyDown(KeyCode.Return))
{
returnPressed = true;
input = keyboardInput;
}
yield return 0;
}
returnPressed = false;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613080306im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Using a Coroutine to wait for user selection? 2 Answers
Simultaneous Unity & Command Prompt? 0 Answers
Assertion Failed? 0 Answers
Issue within my code (not sure with what exactly) 1 Answer
Yielding in a loop only as needed? 0 Answers