Hi!
Im having some problems with understanding coroutines. My goal is to have multiple coroutines in while(true) loop with those couroutines running on different(and dynamic) intervals. Right now i have:
function Start()
{
Loop();
}
function Loop()
{
while(true)
{
Do1;
Do2;
Do3;
Do4;
//...
}
}
function Do1()
{
WaitForSeconds(4);
Print("This will print every 4 seconds");
}
function Do2()
{
WaitForSeconds(2);
Print("This will print every 2 seconds");
}
function Do3()
{
WaitForSeconds(14.34);
Print("This will print every 14.34 seconds");
}
...
Of course that there is an infinite loop, without any “yield” in it. Or maybe not? Placement of yield is bit difficult to understand for me.
Anyone know how to achieve this?
Maybe you need to use InvokeRepeating(“yourFunction”,delayInSeconds,frequencyInSeconds); it’s very precise. It basicaly calls your function at fixed time intervals after a delay. Precision is not perfect, but pretty good for most uses. Use CancelInvoke() to stop calling. It’s in the docs too.
P.S.:InvokeRepeating doesn’t need your function to have a yiel statement. In your script, you could add yield WaitForSeconds(timeInSeconds); but it is less precise.
The coroutine master here is @Eric5h5, but as far as I know, you should do it this way:
function Start(){
Do1(); // fire coroutine 1
Do2(); // fire coroutine 2
Do3(); // fire coroutine 3
}
function Do1(){
while (true){
Print("This will print every 4 seconds");
yield WaitForSeconds(4); // return control to the system, and resume here in 4 seconds
}
}
function Do2(){
while (true){
Print("This will print every 2 seconds");
yield WaitForSeconds(2);
}
}
function Do3(){
while (true){
Print("This will print every 14.34 seconds");
yield WaitForSeconds(14.34);
}
}
From my experience, coroutines work this way: when you call a coroutine (a routine that contains at least one yield), the system creates a new coroutine instance and executes it until the first yield is found; at this point, the coroutine is interrupted and control returns to the caller routine; the instance created will be resumed automatically each new update cycle in the instruction following the yield, and execute until a yield is found, when it stops executing and let the system run free until the next update cycle occurs.
In the case above, Start will call coroutine Do1, which will return to Start when the first yield is found; Start will then call coroutine Do2, which will also return in the first yield, and finally it will call coroutine Do3, which will return in the first yield like the others. Since there are no more instructions, Start ends - but the coroutines started are still running, and continue printing messages at the defined intervals due to the while (true) infinite loop.