A* Pathfinding Project  4.1.20
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
MultiTargetPathExample.cs

This example shows how to use a MultiTargetPath using the Seeker.StartMultiTargetPath method.This script should be attached to a GameObject with a number of children and a Seeker component. This example is only valid when the pathsForAll parameter is set to true, if it is set to false, you can get the path info in the same way as a standard path.

What this script will do is to create a single MultiTargetPath which finds the shortest path from the GameObject to all of the children of the GameObject. It will then draw all those paths and you should be able to see them in the scene view for 10 seconds.

Version
Tested in the A* Pathfinding Project 4.1.7
A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here


using UnityEngine;
using Pathfinding;
using System.Collections.Generic;
public class MultiTargetPathExample : MonoBehaviour {
void Start () {
// Find the Seeker component
Seeker seeker = GetComponent<Seeker>();
// Set the target points to all children of this GameObject
Vector3[] endPoints = new Vector3[transform.childCount];
int c = 0;
foreach (Transform child in transform) {
endPoints[c] = child.position;
c++;
}
// Start a multi target path
seeker.StartMultiTargetPath(transform.position, endPoints, true, OnPathComplete);
// Alternatively you can create a MultiTargetPath from scratch instead
// MultiTargetPath p = MultiTargetPath.Construct(transform.position, endPoints, null, null);
// seeker.StartPath(p, OnPathComplete);
}
public void OnPathComplete (Path p) {
Debug.Log("Got Callback");
if (p.error) {
Debug.Log("Ouch, the path returned an error\nError: " + p.errorLog);
return;
}
MultiTargetPath mp = p as MultiTargetPath;
if (mp == null) {
Debug.LogError("The Path was no MultiTargetPath");
return;
}
// All paths
List<Vector3>[] paths = mp.vectorPaths;
for (int i = 0; i < paths.Length; i++) {
// Plot path i
List<Vector3> path = paths[i];
if (path == null) {
Debug.Log("Path number "+i+" could not be found");
continue;
}
var color = AstarMath.IntToColor(i, 0.5F);
for (int j = 0; j < path.Count-1; j++) {
// Plot segment j to j+1 with a nice color got from Pathfinding.AstarMath.IntToColor
Debug.DrawLine(path[j], path[j+1], color, 10);
}
}
}
}