- Home /
GetKeyDown Problem
I use Input.GetKeyDown to detect my key state, I think it should return the key state on the specific frame, that is, the moment this key is pressed, shouldn't it? However, I find out that this function actually reacts twice during my test in the Update function like this:
void Update() { if( Input.GetKeyDown( KeyCode.W ) ) { Debug.Log( "Print Something" ); } }
Whenever I press W, the Log appears twice. Is there any alternative if I want to get the frame when a key is pressed?
This should be working fine. I don't see any flaw in this.
Answer by daksheshpatel · Apr 24, 2012 at 11:56 AM
//Take bool variable and set it to false when first time it print.Hope it will work.
private bool isprint=true;
Void Update()
{
if(Input.GetKeyDown(KeyCode.W) && isprint)
{
Debug.Log("PrintSomething");
isprint=false;
}
}
$$anonymous$$akes no difference. I think he has attached the same script to different gameObjects.
Answer by ritud · Apr 24, 2012 at 12:00 PM
Thank for your answer. I find that it is my mistake. GetKeyDown will react once in the Update function but twice in the OnGUI function.
Never use the Input class in OnGUI. OnGUI is an event processing - callback which get called several times per frame. You should use the Event class in OnGUI. Input should only be used in Update() or LateUpdate()
OnGUI usually get called two times per frame (Layout event and repaint event) but it might get called multiple times for example a keydown event
Answer by aldonaletto · Apr 24, 2012 at 12:07 PM
I think @fafase is right: it seems you have a duplicate script case - two objects with this script, or this script attached twice to the same object.
To check this, add this debug code to your script:
static int count = 0;
void Start(){ count += 1; print("Instance "+count.ToString()+" in "+transform.name); } This will print a script instance number and to which object it's attached - make sure that damned Collapse button (Console view) isn't active!