- Home /
Trouble with Time.Timescale
I'm trying to toggle time scaling using a GetKeyDown check. The trouble is that when I press the key, nothing happens. I have no errors in the console, and I've tested that the GetKeyDown and the if statements are working by adding a print event, which works fine. I'm also moving the object along its Y axis using transform.Translate, just to see whether timescaling is working.
Here's the code:
function Update ()
{
transform.Translate (0, 0.02, 0);
if ( Input.GetKeyDown ( "s" ) )
{
if ( Time.timeScale == 1.0 )
{
Time.timeScale = 0.2; //slow time down
print ( "Time slowed." );
}
else
{
Time.timeScale = 1.0; //regular speed
print ( "Time Restored." );
}
}
Like I said, no errors, and the printing is working just fine. So what's the problem here?
Answer by tanoshimi · Feb 21, 2015 at 09:58 PM
Your movement is not framerate-independent, so it won't be affected by Time.timeScale. Update() always runs as often as it can - irrespective of timeScale - and you're moving your transform by 0.02 units every time it is called.
Your translate should be made frame rate independent as follows:
transform.Translate (0, 0.02 * Time.deltaTime, 0);
(You might also need to scale the 0.02 up to around 1 instead)
For more info: http://answers.unity3d.com/questions/270116/timetimescale-seems-doesnt-work-with-update.html
Aye. Just multiplying by Time.deltaTime will make the movement be 0.02 units per second, which is a lot slower than 0.02 units per frame (which it was previously.)
Ohhh, brilliant. What a detailed explanation. Thanks for taking the time to answer. Cleared up more than one thing for me.
Answer by vintar · Feb 21, 2015 at 09:57 PM
Basically your script is saying if time scale != 1 then set it to 1 :) you should set the scale to 0.2 on key down and set it back to 1 on key up.
As that code is only being called on frames in which the 's' key was just pressed, I believe it should be functioning as a toggle perfectly fine.
Your answer
Follow this Question
Related Questions
Timer help please 1 Answer
How do I stop 'timeSinceLevelLoad' without pausing entire game? 2 Answers
Pause & Unpause Different timers 1 Answer
How to change overlay with timer? 0 Answers
Random spawn timer 1 Answer