- Home /
The question is answered, right answer was accepted
Execute code every x seconds with Update()
I want to call a block of code every 0.1 seconds using Update() (assuming that this is the best way to do it), but it tends to run on average every .11 - .12 seconds instead.
private float time = 0.0f;
public float interpolationPeriod = 0.1f;
void Update () {
time += Time.deltaTime;
if (time >= interpolationPeriod) {
time = 0.0f;
// execute block of code here
}
}
Answer by duck · May 11, 2010 at 08:36 PM
See InvokeRepeating. It's designed to do exactly this.
Alternatively, if you particularly want to do it in Update, you could change your code to mark the next event time rather than accumulating the delta time, which will be more accurate:
private float nextActionTime = 0.0f;
public float period = 0.1f;
void Update () {
if (Time.time > nextActionTime ) {
nextActionTime += period;
// execute block of code here
}
}
This does not work. Time.time will always be higher than nextActionTime thus the "execute block of code here" will be executed every frame. It should rather be: void Update () { if (Time.time > nextActionTime ) { nextActionTime = Time.time + period; /execute block of code here/ } }
Answer by marchall_box · Nov 07, 2016 at 07:40 AM
How about running a coroutine function?
IEnumerator DoCheck() {
for(;;) {
// execute block of code here
yield return new WaitForSeconds(.1f);
}
}
and run this in your start or something
StartCoroutine("DoCheck");
This will let the function to run every tenth second. You can change the argument to change time. Hope that helps.
Well, simply the code you want to execute. He just calls an arbitrary method here. I'll edit the answer so it follows the same "style" as the other answers.
AFunc is just any function you want to call I guess.
Using "new" very often is going to generate garbage however.
WaitForSeconds waitForSeconds = new WaitForSeconds(0.1f);
IEnumerator Start()
{
while (true)
{
// Place your method calls
yield return waitForSeconds;
}
}
Something like this should be more memory friendly.
Answer by Joe-Censored · Apr 05, 2017 at 01:03 AM
If you like doing it in update, I would just do a 1 line change to below.
This way if you hit update when time is at 0.11f, you subtract 0.1f and are already at 0.01f before getting to your next update. You'll average out a lot closer to 0.1f in the long run than your original implementation.
private float time = 0.0f;
public float interpolationPeriod = 0.1f;
void Update () {
time += Time.deltaTime;
if (time >= interpolationPeriod) {
time = time - interpolationPeriod;
// execute block of code here
}
}
Answer by ATeyken · Dec 16, 2016 at 03:06 PM
This works for me,
public float period = 0.0f;
void Update()
{
if (period > [Time Interval])
{
//Do Stuff
period = 0;
}
period += UnityEngine.Time.deltaTime;
}