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
If 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}");
}
}
}