Advertisement
gameDevTeacher

Navmesh-ShortestPath

Mar 24th, 2025
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | Gaming | 0 0
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3.  
  4. namespace Scripts.Enemies
  5. {
  6.     public class ChooseClosestTarget : MonoBehaviour
  7.     {
  8.         public Transform[] targets;
  9.         public NavMeshAgent agent;
  10.  
  11.         public void ChooseTarget()
  12.         {
  13.             //Transform closestTarget = null;
  14.             float closestDistance = float.MaxValue;
  15.             NavMeshPath path = null;
  16.             NavMeshPath shortestPath = null;
  17.  
  18.             for (int i = 0; i < targets.Length; i++)
  19.             {
  20.                 if (targets[i] == null)
  21.                 {
  22.                     continue;
  23.                 }
  24.                 path = new NavMeshPath();
  25.  
  26.                 if (NavMesh.CalculatePath(transform.position, targets[i].position, agent.areaMask, path))
  27.                 {
  28.                     float distance = Vector3.Distance(transform.position, path.corners[0]);
  29.  
  30.                     for (int j = 0; j < path.corners.Length; j++)
  31.                     {
  32.                         distance += Vector2.Distance(path.corners[j-1], path.corners[j]);
  33.  
  34.                         if (distance < closestDistance)
  35.                         {
  36.                             closestDistance = distance;
  37.                             shortestPath = path;
  38.                         }
  39.                     }
  40.                 }
  41.  
  42.                 if (shortestPath != null)
  43.                 {
  44.                     agent.SetPath(shortestPath);
  45.                 }
  46.             }
  47.         }
  48.  
  49.         private void OnGui()
  50.         {
  51.             if (GUI.Button(new Rect(10, 10, 100, 30), "Move To Target"))
  52.             {
  53.                 ChooseTarget();
  54.             }
  55.         }
  56.     }
  57. }
Tags: C#
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement