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!

GetKey returns TRUE as long as the key is pressed. You want to use Input.GetKeyDown instead.

Don’t use Input in OnGUI. Use Event.current instead, such as Event.current.type == EventType.KeyDown.