Что такое time deltatime unity
Time.deltaTime
Success!
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
Submission failed
For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
Description
The completion time in seconds since the last frame (Read Only).
This property provides the time between the current and previous frame.
Use Time.deltaTime to move a GameObject in the y direction, at n units per second. Multiply n by Time.deltaTime and add to the y component.
MonoBehaviour.FixedUpdate uses fixedDeltaTime instead of deltaTime. Do not rely on Time.deltaTime inside MonoBehaviour.OnGUI. Unity can call OnGUI multiple times per frame. The application use the same deltaTime value per call.
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
You’ve told us this page needs code samples. If you’d like to help us further, you could provide a code sample, or tell us about what kind of code sample you’d like to see:
You’ve told us there are code samples on this page which don’t work. If you know how to fix it, or have something better we could use instead, please let us know:
You’ve told us there is information missing from this page. Please tell us more about what’s missing:
You’ve told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You’ve told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You’ve told us there is a spelling or grammar error on this page. Please tell us what’s wrong:
You’ve told us this page has a problem. Please tell us more about what’s wrong:
Thanks for helping to make the Unity documentation better!
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright © 2020 Unity Technologies. Publication Date: 2021-02-24.
Какую основную функцию выполняет Time.deltaTime в Unity?
Я учусь разработке игр в Unity. Недавно я получил структуру для функции Time.deltaTime во время кода, который я изучал из учебников. Я искал об этом для лучшего понимания, но не понял основной цели его использования, как это объясняется на профессиональном уровне. Короче говоря, я хочу несколько простых объяснений. Итак, я могу понять из этого.
3 ответа
Рендеринг и выполнение скрипта требует времени. Это отличается каждый кадр. Если вы хотите
Чтобы обрабатывать кадры разной длины, вы получаете «Time.deltaTime». В Update он сообщит вам, сколько секунд прошло (обычно это доля, например, 0,00132), чтобы закончить последний кадр.
Если вы теперь переместите объект из A в B, используя этот код:
Это будет двигаться 0,05 единиц на кадр. После 100 кадров он переместился на 5 единиц.
Таким образом, вашему объекту потребуется 1-5 секунд, чтобы пройти это расстояние.
Но если вы сделаете это:
Он будет двигаться 5 единиц в 1 секунду. Независимо от частоты кадров. Потому что, если у вас есть 10000 кадров в секунду, deltaTime будет очень очень маленьким, поэтому он будет перемещаться лишь очень маленьким битом в каждом кадре.
Примечание. В FixedUpdate() он технически не на 100% одинаков для каждого кадра, но вы должны действовать так, как будто он всегда равен 0.02f или каков бы ни был установлен физический интервал. Независимо от частоты кадров Time.deltaTime в FixedUpdate() вернет fixedDeltaTime
Это свойство предоставляет время между текущим и предыдущим кадром.
Вы можете использовать это, например, для проверки частоты кадров. Также, как сказано здесь
Understanding Time.deltaTime
Most of the people (including me) who start with Unity are having a problem with learning Time.deltaTime. To understand how it works, firstly, I will explain its definition. Then I will show a step-by-step example.
By definition, Time.deltaTime is the completion time in seconds since the last frame. This helps us to make the game frame-independent. That is, regardless of the fps, the game will be executed at the same speed. Let’s understand what this means:
Suppose, our game runs at 60 fps. It means that the game is updating 60 times per second, in other words, there are 60 frames.
Note: FPS stands for frames per second
Now, let’s have a look at to the time between frames:
Firstly, the game start, frame 1 is executing, then frame 1 finish, so frame 2 is executing. Time.deltaTime started to calculate when frame 1 ends and finished calculating when frame 2 ends. Let’s see the image below to understand it:
Note: Its value is changing continuously, for this example, I just used 0.05
As we understood what does that mean, let’s see the usage of it and why we are using it:
Always, when we want to move an object, no doubt we use an Update() method.
Note: Update() method is called once per frame
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.
3 Answers 3
Time.deltaTime is simply the time in seconds between the last frame and the current frame. Since Update is called once per frame, Time.deltaTime can be used to make something happen at a constant rate regardless of the (possibly wildly fluctuating) framerate.
So if we just say obj.transform.position += new Vector3(offset, 0, 0); in our update function then obj will move by offset units in the x direction every frame, regardless of FPS.
However if we instead say obj.transform.position += new Vector3(offset * Time.deltaTime, 0, 0); then we know that obj will move offset units every second as every frame it will move the fraction of offset corresponding to how much time that frame took.
Rendering and script execution takes time. It differs every frame. If you want
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:
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:
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.
Какую основную функцию Time.deltaTime выполняет в Unity?
Как улучшить вашу сердечно-сосудистую систему, частоту сердечных сокращений, выносливость, выносливость и фитнес
Я изучаю разработку игр в Unity. Недавно я получил структуру функции Time.deltaTime во время кода, который я изучал из руководств. Я искал его для лучшего понимания, но не понял основную цель его использования, поскольку это объясняется профессиональным образом. Короче, мне нужно простое объяснение. Итак, я могу понять из этого.
Рендеринг и выполнение скрипта требует времени. Каждый кадр отличается. Если вы хотите
60 кадров в секунду, у вас не будет стабильных кадров в секунду, но будет разное количество времени на прохождение каждого кадра. Вы можете подождать, если вы работаете слишком быстро, но вы не можете пропустить рендеринг, если вы работаете медленнее, чем ожидалось.
Чтобы обрабатывать кадры разной длины, вы получаете «Time.deltaTime». В Update он сообщит вам, сколько секунд прошло (обычно это дробная часть, например 0,00132), чтобы закончить последний кадр.
Если вы теперь переместите объект из A в B с помощью этого кода:
Он будет перемещаться на 0,05 единицы за кадр. После 100 кадров он переместился на 5 единиц.
Таким образом, вашему объекту потребуется 1-5 секунд, чтобы переместиться на это расстояние.
Но если вы сделаете это:
он переместится на 5 единиц за 1 секунду. Независимо от частоты кадров. Потому что, если у вас 10000 кадров в секунду, deltaTime будет очень маленьким, поэтому он перемещается только на очень маленький бит за каждый кадр.
Примечание: в FixedUpdate() Технически это не на 100% то же самое в каждом кадре, но вы должны действовать так, как будто это всегда 0,02f или что бы вы ни установили для физического интервала. Независимо от частоты кадров, Time.deltaTime в FixedUpdate() вернет fixedDeltaTime
Итак, если мы просто скажем obj.transform.position += new Vector3(offset, 0, 0); в нашей функции обновления тогда obj пройдёт мимо offset единиц в направлении x каждый кадр, независимо от FPS.
Однако если мы вместо этого скажем obj.transform.position += new Vector3(offset * Time.deltaTime, 0, 0); тогда мы знаем, что obj поедет offset единиц каждую секунду, так как каждый кадр будет перемещать долю offset соответствует тому, сколько времени занял этот кадр.
Это свойство обеспечивает время между текущим и предыдущим кадрами.
Вы можете использовать это, например, для проверки частоты кадров. Также, как сказано здесь