Search code examples
c#unity-game-enginenavmesh

How can I find out the route to the NavMeshAgent target


I want to know the route in advance before the hero walks through it, and draw it by means of line Render, tell me if it is possible to find out in any way the route from the agent without letting the body in front of him that he would have already drawn the line, I would be very grateful for any information

In the screenshot, the hero moves through the points using NavMeshAgent, can I find out the route or points to the target

enter image description here


Solution

  • public class DisplayedPath : MonoBehaviour
    {
        public LineRenderer line; //to hold the line Renderer
        public Transform target; //to hold the transform of the target
        public NavMeshAgent agent; //to hold the agent of this gameObject
    
        private void Start()
        {
            line = GetComponent<LineRenderer>(); //get the line renderer
            agent = GetComponent<NavMeshAgent>(); //get the agent
                                                  //   target = transform;
            StartCoroutine(getPath());
        }
    
        public IEnumerator getPath()
        {
            // line.SetPosition(0, transform.position); //set the line's origin
    
            agent.SetDestination(target.position); //create the path
            yield return new WaitForEndOfFrame(); //wait for the path to generate
    
            DrawPath(agent.path);
    
            agent.Stop();//add this if you don't want to move the agent
        }
    
        public void DrawPath(NavMeshPath path)
        {
            if (path.corners.Length < 2) //if the path has 1 or no corners, there is no need
                return;
    
            line.SetVertexCount(path.corners.Length); //set the array of positions to the amount of corners
    
            line.SetPosition(0, transform.GetChild(0).position); //set the line's origin
    
    
            for (var i = 1; i < path.corners.Length; i++)
            {
                Vector3 up = path.corners[i];
                up.y += 1.5f;
                line.SetPosition(i, up); //go through each corner and set that to the line renderer's position
            }
        }
    }
    

    Thank TEEBQNE.