title: Dynamic Pathfinding A* Unity3D C#
body: <p>I'm trying to use A* pathfinding in Unity3D, and it works if the target remains stationary. However, if the target moves, the units will still follow the same path. Find the code for each unit below (attached to the seeker objects):</p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  
  public class Unit : MonoBehaviour {
  
      public Transform target;
      float speed = 20;
      Vector3[] path;
      int targetIndex;
  
  void Start() {
      PathRequestManager.RequestPath(transform.position,target.position, OnPathFound);
  }
  
  public void OnPathFound(Vector3[] newPath, bool pathSuccessful) {
      if (pathSuccessful) {
          path = newPath;
          StopCoroutine("FollowPath");
          StartCoroutine("FollowPath");
      }
  }
  
  IEnumerator FollowPath() {
      Vector3 currentWaypoint = path[0];
  
      while (true) {
          if (transform.position == currentWaypoint) {
              targetIndex ++;
              if (targetIndex &gt;= path.Length) {
                  yield break;
              }
              currentWaypoint = path[targetIndex];
          }
  
  
          transform.position = Vector3.MoveTowards(transform.position,currentWaypoint,speed * Time.deltaTime);
          yield return null;
  
      }
  }
  
  public void OnDrawGizmos() {
      if (path != null) {
          for (int i = targetIndex; i &lt; path.Length; i ++) {
              Gizmos.color = Color.black;
              Gizmos.DrawCube(path[i], Vector3.one);
  
              if (i == targetIndex) {
                  Gizmos.DrawLine(transform.position, path[i]);
              }
              else {
                  Gizmos.DrawLine(path[i-1],path[i]);
              }
          }
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>now if I try to use it for dynamic pathfinding (target moving around, and paths updating) by changing void Start() to void Update(), this will not work. The response will cause weird unit behaviour, moving forth and back all the time or not completing the path etc.
  Now I don't know the exact cause for this, might be because of coroutines?
  Anyway, how could I alter the code so that correct dynamic pathfinding will be the result?</p>
  
  <p>Thanks in advance!</p>
  
  <p><em>P.S. all remaining source code is to be found here:</em> <a href="http://bit.ly/pathfindingSource" rel="nofollow">http://bit.ly/pathfindingSource</a></p>