- Home /
Loop a function, once per second, X number of times
I need to call a function once per second for X number of times. How can I do this?
I can't use an IEnumerator because "yield return new WaitForSeconds(5);" inside of a For Loop exits the For Loop, and it only runs one time.
I can't use InvokeRepeating, because I need to loop X number of times.
Been at this for an hour or 2, can't figure out any way to: Loop a function, once per second, X number of times.
Just like this: (But this code only runs one time)
for(int i=0; i < total; i++){
yield return new WaitForSeconds(1f);
}
I am using it inside of a Coroutine, but because it "returns new" it only runs the code once, and then it returns a new, so the For loop only runs one time. So how to run a For Loop that only loops once per second?
Still am unable to find any answer to this question, on this site or Google. $$anonymous$$y question is: how to run a For Loop that only loops once per second?
You need to show us your entire code. Im not convicned that you are launching the coroutine correctly.
Answer by Yword · Nov 24, 2014 at 04:38 AM
Maybe you can try the following script:
using UnityEngine;
using System;
using System.Collections;
public class TestInvokeMethod : MonoBehaviour
{
private void Start()
{
// Test invoke the method "TestPrintTime" 5 times, once per second
StartCoroutine(InvokeMethod(TestPrintTime, 1, 5));
}
private void TestPrintTime()
{
Debug.Log(Time.time);
}
public IEnumerator InvokeMethod(Action method, float interval, int invokeCount)
{
for (int i = 0; i < invokeCount; i++)
{
method();
yield return new WaitForSeconds(interval);
}
}
}
Amazing! This is exactly what I was looking for. $$anonymous$$uch appreciated :)
Your answer
Follow this Question
Related Questions
C# simple delay execution without coroutine? 2 Answers
Calling a function only once in Update 6 Answers
InvokeRepeating work only once 1 Answer
How do I...? [scripting help] 2 Answers
Skipping over timer 1 Answer