How to slow a 'for' loop down, in pathfinder script

Hi,

I am trying to make my object move along a route in a path finder script. I have the guy moving but he moves to fast. I am using a for loop to like this;

public void Moving ()
{
    Node player = theGrid.NodeFromWorldPoint(warrior.transform.position);

    //theGrid.path.Reverse();
    foreach (Node n in theGrid.path)
    {
        if (theGrid.path != null)
            if (theGrid.path.Contains(n))

                **for (i = 1; i < theGrid.path.Count; i++)
                    
                    warrior.transform.position = Vector3.MoveTowards(warrior.transform.position, 
                    theGrid.path[0].worldPosition, 0.1f);**
                    
    }
}

but as the for loop cycles rapidly my object also moves rapidly. Any suggestions on how to slow the for loop? I tried to use Invoke but couldn’t get it to work.

full pathfinder, grid and node script is here;

Good day.

You need to use a corrutine, so you can make for example that code executes only 1 for iteration every frame, (not all of them) or make it wait X seconds between iterations.

use this:

 public IEnumerator Moving ()
 {
     Node player = theGrid.NodeFromWorldPoint(warrior.transform.position);
     //theGrid.path.Reverse();
     foreach (Node n in theGrid.path)
     {
         if (theGrid.path != null)
             if (theGrid.path.Contains(n))
                 **for (i = 1; i < theGrid.path.Count; i++)
                     
                     warrior.transform.position = Vector3.MoveTowards(warrior.transform.position, 
                     theGrid.path[0].worldPosition, 0.1f);**
                     yield return null;                         
     }
 }

Now, when coe reaches the “yield return null” it will leave the Moving() method, and will continue at next frame with the next for iteration.

You can delay even more replacing the yield command for this (put the seconds you want):

yield return new WaitForSeconds(3);

Ah!

Think that you need to call this method as a corrutine (is not void), so use this to call it:

StartCorrutine( Moving () );

AS you may see corrutines works little different from void methods. You should go take a look at some tutorial. If need to be a neverstop process, you must call it again in the last line of the method, outside the for.

Bye!