[HOW] Quit the game only after pressing Back button TWICE
I am making an android game. As a norm I think pressing the back button twice should close the application and thats what I aim to do in my game. However, I am not sure of how to code so that the if condition for the first time back button is pressed won't be skipped and cause the game to quit straight away. This is what I have now:
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
isPaused = true;
pauseGame();
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
}
}
Answer by NoseKills · Dec 21, 2015 at 11:33 PM
You have basically 2 mistakes in your code.
Input.GetKey() returns true every time Update is called and the key is pressed... Just check the Unity Manual if you have trouble with Unity's funtions. Since Update is called all the time in rapid succession, it's very probable that the user will have the key pressed during multiple Update() calls even if he tries to press it very quickly. Use Input.GetKeyDown() instead because that happens only once when the button is pressed and doesn't happen again until it's released and pressed again.
The second issue is that even with GetKeyDown() both your if's will happen at once because the condition in them is the same.
You already pause your game when the button is pressed. Just use that as the condition for the second press.
private void Update() {
if (Input.GetKey(KeyCode.Escape)) {
if (!isPaused) { // if game is not yet paused, ESC will pause it
isPaused = true;
pauseGame();
} else { // if game is paused and ESC is pressed, it's the second press. QUIT
Application.Quit();
}
}
}
Answer by saadali211 · Sep 09, 2019 at 02:44 PM
Here is the code
int click = 0;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
click++;
StartCoroutine(ClickTime());
if (click > 1)
{
print("Exit Game!");
}
}
}
IEnumerator ClickTime()
{
yield return new WaitForSeconds(0.5f);
click = 0;
}
Your answer
Follow this Question
Related Questions
The bool activates and deactivates but the script in the if statement doesn´t work 1 Answer
Problem with IF-statement 2 Answers
How to turn turn off/on a collider with a boolean from another script 1 Answer
AudioSource in Update 1 Answer
Project Spark to C# - Started To, While, and No Longer 1 Answer