Shows how to find the closest target of many possible.In the pro version, this is easily achieved with the MultiTargetPath (see the corresponding example and docs), but in the free version it requires requesting multiple paths and comparing their lengths instead of a single path request. This is a bit more tedious and also slower than the MultiTargetPath, but it is possible nevertheless.
- Since
- Written for 3.2 but comments are added in places where adjustments would have to be made to get it to work on 3.1.x
using UnityEngine;
using System.Collections;
using Pathfinding;
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++)
lastPaths[i].Error();
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);
}
}
}
}