Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What main function does Time.deltaTime perform in Unity?

I'm learning game development in Unity. I recently got struct to the Time.deltaTime function during the code i was learning from the tutorials. I have searched about it for better understanding but not learned the main purpose of using it as it is explained in a professional way. In short I want some easy explanation. So, I can understand from it.

like image 857
Hamza Saif Avatar asked Oct 25 '25 01:10

Hamza Saif


1 Answers

Rendering and script execution takes time. It differs every frame. If you want ~60 fps, you will not have stable fps - but differing amounts of time passing each frame. You could wait if you are too fast, but you cannot skip rendering when you are slower than expected.

To handle different lenghts of frames, you get the "Time.deltaTime". In Update it will tell you how many seconds have passed (usually a fraction like 0.00132) to finish the last frame.

If you now move an object from A to B by using this code:

object.transform.position += Vector3.forward * 0.05f;

It will move 0.05 Units per frame. After 100 frames it has moved 5 Units.

Some pcs may run this game at 60fps, others at 144 hz. Plus the framerate is not constant.

So your object will take 1-5 seconds to move this distance.

But if you do this:

object.transform.position += Vector3.forward * 5f * Time.deltaTime;

it will move 5 units in 1 second. Independent of the framerate. Because if you have 10000 fps the deltaTime will be very very small so it only moves a very tiny bit each frame.

Note: In FixedUpdate() its technically not 100% the same every frame, but you should act like it's always 0.02f or whatever you set the physics interval to. So independent from the framerate, the Time.deltaTime in FixedUpdate() will return the fixedDeltaTime


edit: Here is a nice comparison video I made: enter image description here

please watch the video on imgur

Red Cube: transform.position += Vector3.right * (1f / 60f);

Green Cube: transform.position += Vector3.right * Time.deltaTime;

framerate is locked to 60 fps! (using Application.targetFrameRate = 60;

You can see, the green cube is hitting the right wall always at 5, 10, 15, 20, 25 ... At first they look synchronized, but once I jiggle the window, some frames are dropped (may be an editor thing, but there are tons of reasons for frame-drops in a real game). The red cube never catches up to the green one, the dropped frames are never repeated.

That shows using deltaTime is a lot more consistent + it gives you a nice bonus: You can adjust the timescale using Time.timeScale = .5f; to make a slowmotion!

like image 107
KYL3R Avatar answered Oct 26 '25 14:10

KYL3R