onkeydown problem

Anyone know why the onkeydown code gets called twice ? or anyway to fix it ? kinda driving me crazy

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…

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.

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)
  aKeyDown = true;
 .. process ..
  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: Mac Keys not showing up, or very strangely... - Questions & Answers - Unity Discussions