Using the Unity Nav Mesh Agent

The Structure is setup with a Nav Mesh, now it’s time to create a navigation aware object in the scene; the key piece to make this work is the Nav Mesh Agent.

Let’s take the simple approach and create a capsule with a small cylinder child object to indicate the z-forward facing rotation to use as a navigation object.

NavMeshAgent1

Select the Capsule object and add a “Nav Mesh Agent” in the Inspector.

NavMeshAgent2

No need to change the default values. The next step is to create a navigation control script, let’s call it “NavScript.cs” and assign it to the Capsule. The script simply passes the destination to the Nav Mesh Agent.

using UnityEngine;
using System.Collections;

public class NavScript : MonoBehaviour
{
    private Vector3 destination;
    private NavMeshAgent agent;

    public void SetDestination(Vector3 pos)
    {
        destination = pos;
        agent.SetDestination(destination);
    }

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        destination = transform.position;
    }
}

Create an InputController.cs script to manage the mouse clicks to the Structure and pass the location to the NavScript.  Create an empty GameObject called “SceneControllers” to parent the input controller script and assign the capsule object to the input controller parameter.

using UnityEngine;

public class InputController : MonoBehaviour
{    
    public GameObject Character;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Vector3 resultVector3 = Vector3.zero;
            Vector2 pos = Input.mousePosition;
            Ray ray = Camera.main.ScreenPointToRay(pos);
            RaycastHit[] hits;
            hits = Physics.RaycastAll(ray);

            for (int i = 0; i < hits.Length; i++)
            {
                RaycastHit hit = hits[i];
                if (hit.transform.gameObject.tag.Equals("Floor"))
                {
                    resultVector3 = hit.point;                    
                    Character.GetComponent<NavScript>().SetDestination(resultVector3);
                    break;
                }
            }
        }
    }
}

Create a new Tag in the Inspector named “Floor” and set the Structure Tag to “Floor” to enable the hit detection with the Raycast code in the input controller script.

NavMeshAgent3

Run the Scene and click on the structure to set a destination and watch the capsule head towards it.

For questions, comments or contact – Twitter @rlozada