- Home /
onkeydown problem
Anyone know why the onkeydown code gets called twice ? or anyway to fix it ? kinda driving me crazy
Answer by jahroy · May 27, 2011 at 04:41 AM
If you're checking for keyboard input by calling Input.GetKeyDown() from an OnGUI() function, it could return true multiple times. This is because OnGUI can get called more than once in a given frame.
If you call Input.GetKeyDown() from Update instead, it will only return true once.
Another option is to use Event.current to check for keyboard input and to call Event.Use() afterwards so the event isn't used again by your GUI.
I'm sure there are other options as well...
Answer by Joshua · May 26, 2011 at 11:53 PM
It must be a mistake in your code. OnKeyDown get's called when the key is pressed and will not get called again untill the key is released and re-pressed.
Answer by DaveA · May 26, 2011 at 11:56 PM
It's probably the (hardware or OS) 'auto-repeat' setting for your machine. If you don't want to muck with that, you need to keep a boolean that says 'key is down', something like:
bool aKeyDown = false;
OnKeyDown() // or Input.GetKeyDown, etc.
{
if (aKeyDown)
return;
aKeyDown = true;
.. process ..
)
OnKeyUp()
{
aKeyDown = false;
}
I actually made a boolean array big enough to hold all key codes so I could test for all of them.
More info here: http://answers.unity3d.com/questions/57147/mac-keys-not-showing-up-or-very-strangely.html