2D pathfinding, new path after old

Hi! I’ve got a project in which I have AI that are supposed to find out what tasks need doing, move to the nearest one, carry out the task, then find the next. For this to work I need to create a path from the agent to its task, have the agent move follow it, have them carry out the task, then create a path to the next task and so on. However after reaching and carrying out the first task, the path used to do so remains on the scene view and the agent stays put and doesn’t look for a new task. Here’s the code; thanks in advance for any suggestions!

private void FindAndAct(string taskTag, int digDamage, Delegate function)
	//Get list of tasks
	currentTasks = GameObject.FindGameObjectsWithTag (taskTag);

	//Create instance of task to be carried out
	GameObject nearestTask = gameObject;

	//Create instance of current position
	pos = new Vector3 (transform.position.x, transform.position.y, 0f);

	//While there is at least one path
	while (currentTasks.Length != 0)
		//Set nearestTask to be the nearest task as determined by ChooseNearestInRange
		nearestTask = ChooseNearestInRange(pos, currentTasks, 10);
		//Make this the target
		target = nearestTask.transform;
		//Start path
		seeker.StartPath(transform.position, target.position, OnPathComplete);
		if (path == null)
			//We have no path to move after yet
		if (currentWaypoint >= path.vectorPath.Count) 
			//Clear path
			path = null;
			//Clear target
			target = null;

			//Carry out task

			//Remove nearestTask from array currentTasks
			List<GameObject> list = new List<GameObject>(currentTasks);
			currentTasks = list.ToArray();

		//Direction to the next waypoint
		Vector3 dir = (path.vectorPath [currentWaypoint] - transform.position).normalized;
		dir *= speed * Time.fixedDeltaTime;
		this.gameObject.transform.Translate (dir);
		//Check if we are close enough to the next waypoint
		//If we are, proceed to follow the next waypoint
		if (Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]) < nextWaypointDistance) {


The paths are not calculated instantly. In order to smooth out the FPS and make sure that lots of units requesting a path at the same time doesn’t cause the game to lag, path requests are calculated over several frames. So the OnPathComplete method will probably be called the next frame (or maybe the frame after that). I suspect that your if (path == null) call will be true.

You can block until the path is completed using AstarPath.WaitForPath, but I don’t recommend that unless you really need to. You can also wait for the path in a coroutine using Path.WaitForPath (not to be confused with AstarPath.WaitForPath).

I would suggest that you structure your code around a coroutine like

IEnumerator DoStuff () {
   // set the target to the first task
   while (unit has not reached the target) yield return null 
   // set the target to the second task
   while (unit has not reached the target) yield return null 
   // ...