- Home /
Timer repeated function, Coroutine?
I am trying to create a function that runs on a set interval and updates a variable:
// Run this every set interval
void RepeatingFunction() {
someVariable++;
}
I was wondering if this would be an opportunity to use a co-routine and WaitForSeconds? The problem is, I'm unsure as to how to make the function repeat, I tried this:
void Start() { StartCoroutine(RepeatingFunction()); }
private IEnumerator RepeatingFunction() { yield return new WaitForSeconds(pathfindFrequency);
someVariable++;
RepeatingFunction();
}
But unfortunately it doesn't work. Could anyone suggest as to how I can achieve this? For the record, it is part of a pathfinding script, I want to repeat the function so I can get the closest node every set interval.
Answer by Peter G · Apr 24, 2011 at 12:06 AM
You can use InvokeRepeating(). It is probably the easiest way.
void Start () { InvokeRepeating("RepeatingFunction", initalDelay, repeatTime); }
void RepeatingFunction () { Debug.Log(Time.time); //Will print initialDelay + repeatTime * repetitions }
The problem with your code was that you have to call StartCoroutine again to restart the function.
void Start() { StartCoroutine(RepeatingFunction()); }
IEnumerator RepeatingFunction () { yield return new WaitForSeconds(repeatTime);
StartCoroutine( RepeatingFunction() );
}
BUT let me say that you shouldn't use recursion. It's a no no. Instead you should do an infinity loop.
void Start() { StartCoroutine( RepeatingFunction() ); }
IEnumerator RepeatingFunction () { while(true) { //execute code here. yield return new WaitForSeconds(repeatTime); } }
The infinite loop example doesn't seem to delay the call no matter what I set repeatTime to. $$anonymous$$y only concern with using Invoke repeating is that it uses a string lookup which would be slower than the while(true) setup. Any ideas?
Opps! Seems I was passing WaitForSeconds a float, I replaced it with an integer and it's working fine, thanks!
Thank you for this example! I spent 2 hours trying to figure this out, found this answer and it makes everything so simple!
Your answer
![](https://koobas.hobune.stream/wayback/20220613124807im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Trouble with Iterative Coroutine 1 Answer
NullReferenceException in StartCoroutine 1 Answer
Returning an IEnumerator as an int? 1 Answer
Script Initializing help???!!! 2 Answers