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); } } } 1 Answer
You can find the closes point in the the NavMesh with NavMesh.SamplePosition or NavMeshAgent.SamplePathPosition. The second argument maxDistance is used to determine the max distance to search the object.
This returns NavMeshHit. You can access the position with NavMeshHit.position and pass it to NavMeshAgent.SetDestination to move there.
Something like this:
private NavMeshAgent agent; private int waterMask; // Use this for initialization void Start() { agent = GetComponent<NavMeshAgent>(); waterMask = 1 << NavMesh.GetAreaFromName("Water"); } void Update() { NavMeshHit hit; // Check all areas one length unit ahead. if (!agent.SamplePathPosition(NavMesh.AllAreas, 1.0F, out hit)) { if ((hit.mask & waterMask) != 0) { // Water detected along the path... //Move to it agent.SetDestination(hit.position); } } } 2