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
2 Answers
2If you want to do something once a second, you might wanna check out Coroutines.
Here’s a reference: Unity - Manual: Coroutines
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.
Use coroutines as suggested if the action will spawn more than a frame or else use something like the below, you can use timeDelta or fixedTimeDelta whatever makes more sense in your game.
public class Timer: MonoBehaviour
{
private int count = 0;
private float timer = 0f;
private float waitTime = 10f;
private void Update()
{
timer += Time.fixedDeltaTime;
Debug.Log($"{timer}");
if (timer >= waitTime)
{
count++;
timer -= waitTime + Time.fixedDeltaTime;
Debug.Log($"{waitTime} lapsed and count is {count}");
}
}
}
yeh the thing is I didn't want to use the update since this function is called in externally but I was thinking about it tonight and I can just use the update anyway and work with booleans. That way I won't have to use the coroutine. But I don't really want to use the update since I only need this stuff to work everytime a trigger is entered, I don't want it checking if it has to do something forever.
– kaplovski
Thanks for the aid and I didn't know that about Time.deltaTime
– Bioman889