- Home /
How do I make the timeScale not affect the timer?
Hello, I have this timer that starts at the beginning of my game. What I wanted was, when it's counting down from 3, time will be paused with Time.timeScale = 0f; and when it reaches 0, it will unpause with Time.timeScale = 1f;
The problem is, Time.timeScale also pauses my countdowntimer, so it stays stuck at "3." I've tried changing Time.deltaTime to Time.unscaledDeltaTime, but it randomizes my timer, usually having it start from negative onwards.
Is there any other way to have the timeScale not affect the timer?
Any insights on this would be much appreciated!
Answer by RaptorRush · Aug 09, 2020 at 05:15 PM
You can use WaitForSecondsRealtime (in a Coroutine), since it uses unscaled time.
using System.Collections;
using UnityEngine;
public class Example : MonoBehaviour {
private void Start() {
Time.timeScale = 0;
StartCoroutine(Timer());
}
private IEnumerator Timer() {
Debug.Log("Timer start");
yield return new WaitForSecondsRealtime(3);
Debug.Log("Timer end");
Time.timeScale = 1;
}
}
Note: you need StartCoroutine to start the timer.
Hello, this is good and all but unfortunately, I have a text that gets updated and goes down from "3" to "1." If I set the timeScale to 0 in the start method, it doesn't update my timer. Thanks for the suggestion though.
You can try editing the timer display directly in the coroutine:
private static readonly WaitForSecondsRealtime oneSecondDelay = new WaitForSecondsRealtime(1);
private IEnumerator Timer() {
Debug.Log("Timer start");
textReference.text = "3";
yield return oneSecondDelay;
textReference.text = "2";
yield return oneSecondDelay;
textReference.text = "1";
yield return oneSecondDelay;
textReference.text = "0";
Debug.Log("Timer end");
Time.timeScale = 1;
}
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Trying to make a timer work.. 0 Answers
How would I make a timer frame independent? 1 Answer
How to make this display milliseconds? 3 Answers
make a countdown timer 1 Answer