How to get the closest object in the navMesh and making the agent move towards it

At the moment I have a semi-dynamic layout where my agent follows the randomized waypoints and after he reaches one, he deletes said waypoint. However, I want him to scan the closest waypoint to the object. Taking into account vector3.distance goes over obstacles, what are the other solutions.

public NavMeshAgent agent;
    public GameObject[] waypoints // Waypoints
    public Transform[] locations // Waypoint location
    for (int x = 0; x < waypoints.Length; x++) // Sets random position
    {
        if (x < 5) 
        {
            waypoints[x].transform.position = new Vector3(Random.Range(-33.0f, 30.0f), 3.575465f, Random.Range(30.0f, -35.0f));
        }

        for (int z = 0; z < waypoints.Length; z++)
        {
            if (z < 5 && waypoints[z] != null)
            {
                agent.SetDestination(locations[z].position);
            }
        }
    }

Good day.

How many waypoint there are in the map?

You can create a script for each waypoint, that is calculating the distance between itself and the player with

float DistanceToPlayer = Vector3.Distance(transform.position , player.transform.position);

And then in the player have 2 stored variables, a float for distance called “DistanceToWaypoint” and gameobject for waypoint called “Waypoint”, so the waypoints can do this

if (DistanceToPlayer < Player.DistanceToWaypoint)
{
Player.DistanceToWaypoint= DistanceToPlayer
Player.Waypoint = gameObject;
}

So Player will ahve always stored the nearest waypoint in the “Waypoint” variable!

If helped, accept the answer!

Bye!!