- Home /
Timescale not affect timer? (C#)
Hello my fellow Unities! I'm making a 2D mobile survival game, where I have a timer counting upwards that is printed on the screen. I also have a power up, that is used to slow down the enemies and everything around them. Now I have a problem, is it possible to make the timer ignore the Time.Timescale while the power up is in use?
How would I go forward in solving this?
Here's the code for the timer:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TimerScript : MonoBehaviour
{
//Create timer
public static float timer = 0f;
//Create displayed timer
Text text;
void Awake()
{
//Load Text class
text = GetComponent<Text> ();
//Reset the timer
timer = 0f;
}
void Update()
{
//Start the timer and keep it going
timer += Time.deltaTime;
//Write out the timer on the screen
text.text = "" + timer.ToString("F1");
}
}
And here's the code for the power up and when it's in use:
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "PowerUp1")
{
if(Time.timeScale == 1.0f)
{
Time.timeScale = 0.2f;
Destroy(GameObject.FindGameObjectWithTag("PowerUp1"));
}
}
}
Answer by phil_me_up · Mar 15, 2016 at 11:39 AM
You could always just compensate by multiplying Time.deltaTime by the same factor you changed the timescale by.
timer += Time.deltaTime * (1.0f / 0.2f);
You changed your timescale to be 1/5th of the original time, so compensate by counting up 5 times faster.
Answer by Sscia · Mar 15, 2016 at 11:52 AM
There is one property not affected by TimeScale which is Time.unscaledTime, it will return the time passed since the beginning of the game unaffected by the timescale changes.
This solution will require you to alter your algorithm a bit: instead of adding deltaTime to your counter every frame, save Time.unscaledTime when the timer starts running (something like _timerStartTime), and calculate the timer every frame by reducing _timerStartTime from the current Unscaled Time (giving your the current timer)
Here's some code, but it is not machine tested:
void ResetTimer()
{
_timerStartTime = Time.unscaledTime;
}
void Update()
{
...
timer = Time.unscaledTime - _timerStartTime
}
Uhm you can also use Time.unscaledDeltaTime which would be exactly what the OP wants ^^. It's the current deltaTime without any scaling.
Note: As far as i know the unscaledDeltaTime value also has no clamping. So for example if the loading of a scene took very long (for example 3 sec), then Time.unscaledDeltaTime would be 3.0f the next frame. Time.deltaTime is clamped to 0.333 by default to prevent strange effects.