- Home /
How to properly use Time.deltaTime in a for loop?
I'm trying to get this for loop to increase i by 1 every second using Time.deltaTime but whenever I test it out, it runs all the way through in an instant
Answer by Quickz · Apr 20, 2020 at 08:32 PM
If you want to do something once a second, you might wanna check out Coroutines.
Here's a reference: https://docs.unity3d.com/Manual/Coroutines.html
Here's a small example:
using System.Collections;
using UnityEngine;
public class TestScript : MonoBehaviour
{
private void Start()
{
StartCoroutine(DoStuff());
}
private IEnumerator DoStuff()
{
for (int i = 0; i < 5; i++)
{
yield return new WaitForSeconds(1f);
Debug.Log("Hello, world!");
}
}
}
Also about the Time.deltaTime. It's simply a property that contains the number of seconds that passed between current and previous frame. Update runs once per frame, so every update Time.deltaTime will have a different value. If you want to do something every X seconds using Time.deltaTime and an Update method, you can add up the value it contains every frame and use an if statement. I would however prefer using Coroutines in that situation though.
Thanks for the aid and I didn't know that about Time.deltaTime
Your answer
Follow this Question
Related Questions
Delay Player From Using Action Button For A Period Of Time 0 Answers
Why does resetTimer act counter-intuitively? 2 Answers
Android and Time.DeltaTime 0 Answers
Digital Clock Needed For New UI Text 1 Answer
How do I fix this cooldown? 1 Answer