❔ Console.ReadKey() blocking

Hey there. I have this function that is called every frame:
public void Update()
{
if ( !Console.KeyAvailable ) return;

var key = Console.ReadKey(intercept: true);
}
public void Update()
{
if ( !Console.KeyAvailable ) return;

var key = Console.ReadKey(intercept: true);
}
It blocks until a key is pressed instead of setting KeyAvailable back to false... I know this is being called every frame because I can insert a Debug.Log(); return; at the top and I will see it log every frame. However if I put the Debug.Log() after the ReadKey(), it only gets called when you press keys.
10 Replies
Buddy
Buddy2y ago
ReadKey is blocking Also, is this Unity?? There is no console associated with Unity. Do not use the Console class (for Unity)
aaron.frost
aaron.frostOP2y ago
It is a dedicated server console window It is spun up with
[DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AllocConsole();
[DllImport( "kernel32.dll", SetLastError = true )]
static extern bool AllocConsole();
This is Unity
aaron.frost
aaron.frostOP2y ago
Pastebin
ConsoleWindow.cs - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
aaron.frost
aaron.frostOP2y ago
Pastebin
ConsoleInput.cs - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
aaron.frost
aaron.frostOP2y ago
ConsoleInput.Update() is the function causing the problem
Buddy
Buddy2y ago
Well, tough sh*t. ReadKey is blocking. You can maybe use GetAsyncKeyState? https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate But if you want an in-game console window, you can just set up Dear Imgui, or make your own. And I don't recommend using P/Invoke to Windows API in Unity since that will cause issues with cross-platform. Maybe you want to publish for Mac, and whoops. It does not have Windows API. There goes your console Window, and possibly crashes.
arion
arion2y ago
Unity also has an input system you can check out, no windows apis needed
aaron.frost
aaron.frostOP2y ago
Input System doesn't work because Unity is running in batchmode I'll try GetAsyncKeyState
Jester
Jester2y ago
try raw input maybe shouldnt unity have that?
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server