Search code examples
c#unity-game-enginepath-findingnavmesh

Pathfinding to waypoints using NavMesh (Unity)


I want to make a simple script, that guides a NavMesh agent to various waypoints. I am new to Unity so I don't know some basic functions yet, which is instead typed in pseudo code.

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour {

    private Transform target;
    private int wavepointindex = 0;
    public NavMeshAgent agent;

    void Start () {
        target = Waypoints_blue_left.waypoints[0];
    }

    void Update () {
        //Set destination to waypoint
        Vector3 dir = target.position;
        agent.setDestination(dir);

        if (agent is within a close range/touching target waypoint)

            //Remove object if at the last waypoint
            if (wavepointindex == Waypoints_blue_left.waypoints.Length)
                Destroy(gameObject);

            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];

    }
}

Solution

  • void Update() function called each frame. So you need a function that check if the agent arrives to point, set the new destination to it.

    I changed your code to this:

    using UnityEngine;
    using UnityEngine.AI;
    
    public class Path_left_blue : MonoBehaviour 
    {
        private Transform target;
        private int wavepointindex = -1;
        public NavMeshAgent agent;
    
        void Start () 
        {
            EnemyTowardNextPos();
        }
    
        void Update () 
        {
            // agent is within a close range/touching target waypoint
            if (!agent.pathPending && agent.remainingDistance < 0.5f)
            {
                EnemyTowardNextPos();
            }
        }
    
        void EnemyTowardNextPos ()
        {
            if(wavepointindex == Waypoints_blue_left.waypoints.Length - 1)
            {
                Destroy(gameObject);
            }
            else
            {
                // set destination to waypoint
                wavepointindex++;
                target = Waypoints_blue_left.waypoints[wavepointindex];
                agent.SetDestination(target);
            }
        }
    }
    

    EnemyTowardNextPos() function only called when agent arrives to current point.

    I hope it helps you