Find Lowest number in transform array

Hey people, hope you’re well!

So I have a patrol path with various waypoints and a guard following that path. when the guard see the player he wanders over to the last location the player was in view. if the player ducks out of LOS then the guard investigates that position and if he finds nothing he continues his patrol at the last waypointIndex.

However I’d like the guard to just patrol from the closest waypoint from the investigation location.

At the moment I have a transform array of the waypoints and I guess I’d like to measure the distance to these waypoints when he enters the patrol state again and get the lowest float distance and then update the waypointIndex. at the moment I have this.

void CalculateClosestWaypoint()
        foreach (Transform waypointPosition in waypoints)
            float distanceToClosestWaypoint = Vector3.Distance(waypointPosition.position, 


Just stuck on where to go from there. if there’s a more elegant solution please let me know and thanks so much for your time!!

Hi Steve,

In which course and lecture are you?

Hey Nina,

I’m on the RPG course around lesson 54 but I’ve kind of started doing my own little bits on the side to build upon the lectures :slight_smile:
Thanks so much

In that case, @Brian_Trotter will hopefully be able to help you. :slight_smile:

Here’s a method that will return the nearest waypoint to a given position:

       public int FindNearestWaypoint(Vector3 position)
            //Seed our search with the first 
            float nearestDistance = Vector3.Distance(position, waypoints[0].position);
            int result = 0;
            for (int i = 0; i < waypoints.Length; i++)
                //Test distance against each element and replace result with index if lower.
                float testDistance = Vector3.Distance(position, waypoints[i].position);
                if (testDistance < nearestDistance)
                    nearestDistance = testDistance;
                    result = i;
            return result;