Even if no input is given before I switch to another application, my character spins left forever, regardless of new input when I switch back to Unity with Play mode running.
By alt-tab, I assume you’re referring to the Windows standalone platform.
A common problem in Input programming is that when you hold down a key, then alt-tab, the key-up event is lost. So your app is stuck thinking that key is still down. The application needs to be in focus in order to receive these input events. To get out of this, you’d need to hit that key and release it while the app is in focus, which triggers the key up event.
To better deal with this in code, one workaround is to use Input.GetKeyDown instead of Input.GetAxis if you can. Never ever rely on needing both KeyDown and KeyUp events.
Actually, putting alt-tab in the title was misleading.
If I just switch applications with the mouse it works the same.
And I want to use getAxis instead of KeyDown because I want to support gamepads in the future.
To add to this, when I press an arrow key, the getAxis float is something like -0.04 or 0.05 when I detect it in the code above, but when switching back to the Unity Editor in Play mode, it’s stuck full tilt at -1.
I can’t say that this will do what you want , for sure, but maybe you can work this in to use a bool or something to prevent input when focus is lost (/restored):
I’m also experiencing this issue but only on Windows 10. My Mac does not have the issue. With the simplest example possible (NetworkManager and a PlayerCube) between applications, the app that becomes unfocused gets its Horizontal Axis stuck at -1 and it’s Vertical Axis stuck at 1. I was not holding any movements keys when I changed windows, so it’s not a KeyUp event being lost. If I refocus the window and try to move the player cube, the Input remains frozen with some sporadic movement. Unity 5.6.1f1, 64bit, Windows 10
Update
The problem seems to be coming from virtual joystick input. If you look under your Input Settings, you’ll notice you have two entries for Horizontal and Vertical. One is for joysticks, and the other is for keyboards. I just removed my Joystick entries and the problem was resolved. Found this forum post to be helpful in fixing my issue. Input.GetAxis(Horizontal) problem - Questions & Answers - Unity Discussions
I had the same issue in Unity 2017.1.1. The joystick on my gamepad was stiking to -1 and 1. Chaning Joy Num from “Get Motion From All Joysticks” to “Joystick 1” in InputManager fixed the problem for me. Perhaps Windows thought one of my other devices was a joystick, because Windows.