So, I use Time.timescale = 0 to pause my game. When I press the pause button, my game stops. Then when I press it again, the game just starts immediately. I want somekind of a 3 seconds pause time between the paused state and the game state. How should I do that? Here’s my code:
public GameObject pauseCanvas;
public void PauseTheScene ()
{
if (Time.timeScale != 0)
{
Time.timeScale = 0;
pauseCanvas.SetActive (true);
}
else if (Time.timeScale == 0)
{
Time.timeScale = 1;
pauseCanvas.SetActive (false);
}
}
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour
{
private IEnumerator _unscaledTimeRoutine;
public GameObject pauseCanvas;
public void PauseTheScene ()
{
if (Time.timeScale != 0)
{
Time.timeScale = 0;
pauseCanvas.SetActive (true);
}
else if (Time.timeScale == 0)
{
pauseCanvas.SetActive (false);
_unscaledTimeRoutine = DelayResume(3f);
}
}
//Custom routine
IEnumerator DelayResume(float sec)
{
//set t equal to duration that will delayed
float t = sec;
//Keep count down until t <= 0
while (t > 0)
{
t -= Time.unscaledDeltaTime;
yield return null;
}
//when the count down time is out resume game
Time.timeScale = 1;
yield return 0;
}
void Update()
{
if(_unscaledTimeRoutine != null && !_unscaledTimeRoutine.MoveNext())
_unscaledTimeRoutine = null;
//The code above can be break down for better understanding
/*
//Do we have any routine to run ?
if(_unscaledTimeRoutine != null)
{
//if there is then run the routine and check if it is ended ?
bool routineEnded = !_unscaledTimeRoutine.MoveNext();
//if the routine ended then set _unscaledTimeRoutine to null
if(routineEnded)
_unscaledTimeRoutine = null;
*/
}
}
OnUpdate will continue to execute even if the timescale is zero.
You can add Add Some custom code inside Update() may beto resolve the issue.
Hope this will help you.
Ulternatively use iTween With ignoretimescale and pass “comcomplete” method which might execute even if TimeScale is Zero. (This is not tested, but hopefully this will work).