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
Это свойство предоставляет время между текущим и предыдущим кадром.
Вы можете использовать это, например, для проверки частоты кадров. Также, как сказано здесь
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.
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
Русские Блоги
время
Time.Deltatime Я считаю, что все использовали это, и сегодня я проанализирую что-то, связанное с DeltaTime
1. Понимание по определению
Unity3D официальный сайтПравильный Time.Deltatime Учитывая это описание:
The time in seconds it took to complete the last frame (Read Only).
То есть для предыдущего кадра время от начала до конца равно Time.DeltaTime. Мы также можем понять это так:
После обработки этой строки кода в последнем кадре мы возвращаемся к этой строке кода в этом кадре, и время прошло Time.DeltaTime секунд.
Кроме того, согласно определению, мы не трудно ввести, Time.Deltatime Должно бытьСек / кадр。
2. Понимание в использовании
вUnity3D официальный сайтНа это также есть предложение:
If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime. When you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame.
Значение примерно, если вы хотите определить объект каждыйвторойДвигайтесь 10 метров вместо каждогоРамкаДвигайся 10 метров. Пожалуйста, умножьте DeltaTime после 10, чтобы он стал10 m/s。
Может быть, в первый раз, когда вы почувствуете, что это предложение немного волшебно, как вы можете умножить DeltaTime, чтобы заставить объект двигаться в зависимости от времени?
Предположим теперь, что есть переменная скорость = 10 м / с, есть надежда, что во время воспроизведения объект будет двигаться в соответствии с этой скоростью. Итак, когда мы сфокусировались на методе Update, мы подумали о том, какое расстояние нам нужно пройти в каждом кадре, чтобы имитировать скорость движения в реальном состоянии? То есть рассчитать X м / кадр.
От предыдущего кадра к этому кадру время прошло в секундах DeltaTime, и истинная скорость движения составляет 10 м / с, поэтому за истекшее время объект должен двигаться на расстояние DeltaTime * 10, и Это расстояние в точности равно расстоянию, перемещенному от предыдущего кадра к этому кадру.
Согласно этой идее, следующая формула может быть перечислена:
10 м / с × DeltaTime s / frame = X м / frame
И эта формула как раз и есть метод использования, предложенный на официальном сайте.
3.1 Внимание понимание
Unity3D официальный сайтЕсть также некоторые меры предосторожности:
When called from inside MonoBehaviour’s FixedUpdate, returns the fixed framerate delta time.
Сначала напишите код скрипта:
Затем вы можете запустить, чтобы увидеть эффект:
Посредством наблюдения было обнаружено, что время, отображаемое с помощью FixedUpdate, является установленным фиксированным значением 0,02 секунды, и обновление не обязательно, но оно намного меньше времени, отображаемого с помощью FixedUpdate. Таким образом, мы можем заключить, что FixedUpdate также может быть использован напрямую Time.DeltaTime 。
Почему Time.DeltaTime Разные методы могут возвращать разные значения, как этого добиться. Пока я не знаю, я надеюсь, что читатели, у которых есть идеи для реализации, могут оставить сообщение и обменяться.
Note that you should not rely on Time.deltaTime from inside OnGUI since OnGUI can be called multiple times per frame and deltaTime would hold the same value each call, until next frame where it would be updated again.
Смысл не в том, чтобы использовать DeltaTime в OnGUI, потому что OnGUI может вызываться несколько раз в одном кадре. Что касается того, почему вы должны обращать на это внимание в принципе, я считаю, что читатели, которые внимательно прочитали вышеуказанное содержание, могут иметь глубокое понимание.
4. Вывод
Зачем усердно работать и думать о начале. —— Чжоу Синчи







