// Don't put this check inside your for loop:
// code inside the loop only executes if Count is > 0
if (axolotls.Count == 0) {
if (Time.time - lastWanderTime > wanderDuration) {
myAgent.SetDestination(randomDestination(randomWander));
lastWanderTime = Time.time;
}
} else {
// Initialize our search to the worst possibility:
// no target, infinitely far away! (Literally ANYTHING else is better!)
float lowestScore = float.positiveInfinity;
Axolotl closest = null;
Vector3 myPosition = transform.position;
foreach (var axolotl in axolotls) {
// Skip destroyed axolotls (better: make sure they're not in the list!)
if (axolotl == null) continue;
// Don't pay for a square root we don't need.
float score = (axolotl.transform.position - myPosition).sqrMagnitude;
if (score < lowestScore) {
closest = axolotl;
lowestScore = score;
}
}
// "closest" now contains the nearest axolotl.
}
DMGregory ♦
- 141k
- 23
- 258
- 401