Find closest waypoint.

I use the following script to find the closest waypoint for my NPCs to go to. However, the debug logs a list of all the checkpoints and the NPCs do not move to the closest one but to the last one in the list.

  GameObject[] checkpoint = GameObject.FindGameObjectsWithTag("checkpoint");
                {
                    foreach (GameObject go in checkpoint)
                    {
                        ObjectiveControl comp = go.GetComponent<ObjectiveControl>();
                       if (comp != null && comp.waypoint == true*/)
                        {
                            path.Add(comp.transform);
                            currentCheckpoint = FindClosestCheckpoint();
                            Debug.Log(currentCheckpoint);
                        }
                    }
                }

   int FindClosestCheckpoint()
    {
            if (path.Count == 0) return -1;
            int closest = 0;
            float lastDist = Vector3.Distance(this.transform.position, path[0].transform.position);
            for (int i = 1; i < path.Count; i++)
            {
                float thisDist = Vector3.Distance(this.transform.position, path*.position);*

if (lastDist > thisDist && i != currentCheckpoint)
{
closest = i;
}
}
return closest;
}

initialize float lastDist to infinity or something huge… outside the loop.

then inside your loop, when you find something closer… you need to store both closest=i; and ALSO set lastDist = thisDist

also suggest renaming thisDist to closestDist would make things clearer