Use MultiTargetPath with AIPath

For now I’m using AIPath.SearchPath() to search the single target and it works well. but how to search the path for multiple targets in AIPath

Just read the code of MultiTargetPath.cs, and find that the targetPoints are stored in the Vector3[] which will be created every time when MultiTargetPath is constructed. could you replace the Array with List to avoid GC and change

public static MultiTargetPath Construct (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) 


public static MultiTargetPath Construct (Vector3 start, IReadOnlyList<Vector3> targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) 


You can disable the agent’s own path calculations, and then use the SetPath method:

ai.canSearch = false;

If you cannot have a local target array that you re-use, you can use an array pool to avoid this allocation. See ArrayPool - A* Pathfinding Project

would it be possible that I write my own MultiTargetPath with List? Did not find anything like it in the doc.

That’s entirely possible. Just copy-pasting the class (and renaming it) should work.

I can not access some internal variables

Oops. Sorry. That was an oversight. Those should have been accessible. I’ll fix that in the next beta update.

1 Like

After using the custom FixedMultiTargetPath, the AiPath.reachedDestination always return false even if the RemainingDistance is 0.00, though it is fine with your MultiTargetPath. What I’m modifying is just create the array with max possible length at constructor thus it do not need to create a new array every time

After debug, I find the AIPath.destination is not updated after my FixedMultiTargetPath done, so the if-condition is always true, not sure why this field will be updated after MultiTargetPath done

remainingDistance + movementPlane.ToPlane(destination - interpolator.endPoint).magnitude > endReachedDistance

I think I find out the reason why the destination is not updated.

if (path is RandomPath rpath) {
	destination = rpath.originalEndPoint;
} else if (path is MultiTargetPath mpath) {
	destination = mpath.originalEndPoint;

Just extend the AIPath, seems working, let me know if there are some potential problems.

 public class AIPathExtension : AIPath
        protected override void OnPathComplete(Path newPath)
            if (path is FixedMultiTargetPath p)
                destination = p.originalEndPoint;
1 Like