public class MultiTargetFree : MonoBehaviour {
public Transform[] targets = new Transform[0];
private Path[] lastPaths;
private int numCompleted = 0;
private Path bestPath = null;
void Start () {
SearchClosest();
}
public void SearchClosest () {
if (lastPaths != null)
for (int i = 0; i < lastPaths.Length; i++)
if (lastPaths == null || lastPaths.Length != targets.Length) lastPaths = new Path[targets.Length];
bestPath = null;
numCompleted = 0;
for (int i = 0; i < targets.Length; i++) {
ABPath p = ABPath.Construct(transform.position, targets[i].position, OnTestPathComplete);
lastPaths[i] = p;
}
}
public void OnTestPathComplete (Path p) {
if (p.error) {
Debug.LogWarning("One target could not be reached!\n"+p.errorLog);
}
for (int i = 0; i < lastPaths.Length; i++) {
if (lastPaths[i] == p) {
numCompleted++;
if (numCompleted >= lastPaths.Length) {
CompleteSearchClosest();
}
return;
}
}
}
public void CompleteSearchClosest () {
Path shortest = null;
float shortestLength = float.PositiveInfinity;
for (int i = 0; i < lastPaths.Length; i++) {
float length = lastPaths[i].GetTotalLength();
if (shortest == null || length < shortestLength) {
shortest = lastPaths[i];
shortestLength = length;
}
}
Debug.Log("Found a path which was "+shortestLength+ " long");
bestPath = shortest;
}
public void Update () {
if (bestPath != null && bestPath.vectorPath != null) {
for (int i = 0; i < bestPath.vectorPath.Count-1; i++) {
Debug.DrawLine(bestPath.vectorPath[i], bestPath.vectorPath[i+1], Color.green);
}
}
}
}