- Home /
I press ESC once, Unity thinks I've pressed it many times...
Hi. Firstly I want to say I really didn't know what had I to write for title, Or what had I to search in google.
Here's my problem: I'm making a toggle key that should pause the game and show the GUI menu. So I'm using some piece of code like this (in C#):
static bool tgl=false;
void OnGUI()
{
if(Input.GetKey(KeyCode.Escape))
tgl=!tgl;
if(tgl){
//Show GUI and stop the game
}
else{
//Resume the game
}
}
But at this moment, unity engine goes mad and every time I press ESC key on my keyboard, the unity thinks I've pressed it many times (Minimum:8). I figured it out by adding a static int and adding to it by pressing ESC key and showing it at Debug.Log . The number is always even; so game doesn't stop and GUI doesn't display.
How do you make a toggle key?
( Note that I'm quite sure from my GUI and pausing code, because it works as a "Hold" key. )
Thanx in advance!
Answer by Eric5h5 · Oct 03, 2012 at 05:58 PM
Don't use Input in OnGUI. Use Event.current instead, such as Event.current.type == EventType.KeyDown.
I couldn't understand how does that code do, but it's working perfectly. Thanks.
Answer by Demigiant · Oct 03, 2012 at 05:43 PM
GetKey returns TRUE as long as the key is pressed. You want to use Input.GetKeyDown instead.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081830im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to get User Input to Work in OnGUI and Update Functions Please help! 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Hover Over Input Field Before Inputting? 2 Answers