C# Yield WaitForSeconds within For Loop
I am trying to use two yields within a coroutine loop (because I need to iterate out arrays with pauses between each loop).
The first loop works correctly, with all the yields working for the right amount of time. By the second loop, the yield return new WaitForSeconds() begins counting down right away, not waiting for the yield and code before it to complete (it seems). By the time of the third loop, the timing is all off.
I tried using a while loop instead of a for, but got the same result.
I need to loop out my arrays with pauses between each one.
public IEnumerator doPathfinding()
{
for (int i = 0; i < waypoint.Length; i++)
{
// get first waypoint from array
var _waypoint = waypoint[i];
// get node on A* of cloest waypoint
closestPointOnNavmesh = AstarPath.active.GetNearest(_waypoint.transform.position, NNConstraint.Default).clampedPosition;
// Move towards destination
ai.destination = closestPointOnNavmesh;
// Wait until within X range of waypoint
yield return new WaitUntil(() => distanceReached == true);
// Agent is now at waypoint and automatically stops. Wait 5 seconds before looping to next waypoint.
yield return new WaitForSeconds(5f);
}
Debug.Log("Loop End");
}
Answer by vishal · May 18, 2018 at 06:35 AM
@ tcmeric Problem: This way, you are just suspending the coroutine execution until your delegate (distanceReached ) evaluates to true and will resume again when delegate evaluate to true.
Solution: Your coroutine suspension is working as per your expectation so you just need to check the value of your distanceReached variable, if it evaluates to true, break your loop and transfer the control to main caller.