I wanted to stop my game when “P” is pressed and continue it when “P” is pressed again - but at least o,1 seconds later. For this I used the following script:
using UnityEngine;
using System.Collections;
public bool Pause = false;
public bool PauseUmstellbar = true;
void Update ()
{
if (Pause) {
Time.timeScale = 0.00001f;
} else {
Time.timeScale = 1;
}
if (Input.GetKey (KeyCode.P)) {
if(PauseUmstellbar){
PauseUmstellbar=false;
StartCoroutine(PauseUmstellen());
if (Pause) {
Pause = false;
} else {
Pause = true;
}
}
}
}
IEnumerator PauseUmstellen(){
if (Pause) {
yield return new WaitForSeconds (0.000001f);
PauseUmstellbar = true;
} else {
yield return new WaitForSeconds (0.1f);
PauseUmstellbar = true;
}
}
It works but if its Paused it never will be de-paused again. What can I do?
There are a few problems with the way you have written the script. The major problem is that you change pause after you start the coroutine. This causes PauseUmstellen to use wait for 0.1f seconds when pausing. Then you change the timescale to 0.00001 which means your program will allow new pause commands in about 3 hours.
However if you try to move the pause command before the coroutine starts, you wait for 0.0000001f seconds at normal time until the next Update changes the timescale but by then 0.0000001f seconds have passed. To fix this error you should immediately change the timescale upon pausing (it is also more efficent to assign timescale one when it changes).
Here is an example of code (I cleaned it up 2 parts and changed the delay to 0.5f seconds to help me debug it).