Logo my studio is game, portfólio is developer game

Unity NavMesh Available Path

When we work with NavMesh, we always want to know whether or not the agent path is available.

With this script, I can know if on the way has any obstacle that prevents the agent from reaching its final destination:

using UnityEngine;
using UnityEngine.AI;

public class Enemy_unitys : MonoBehaviour
{

    private NavMeshAgent agent;

    [HideInInspector]
    public bool pathAvailable;
    public NavMeshPath navMeshPath;
    [SerializeField] private GameObject toGo;

    private void Start()
    {
        navMeshPath = new NavMeshPath();
        agent = GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        agent.SetDestination(toGo.transform.position);

        CheckPath();


    }

    private void NoPathAng()
    {
        Vector3 direction = agent.destination - agent.transform.position;
        direction.y = 0f;

        if (Mathf.Abs(direction.x) > Mathf.Abs(direction.z))
            direction.z = 0f;
        else
            direction.x = 0f;
        agent.transform.rotation = Quaternion.LookRotation(direction);
    }

    // Forehead if path is free
    private void CheckPath()
    {
        if (CalculateNewPath() == true)
        {
            pathAvailable = true;
            //print("Path available");
        }
        else
        {
            pathAvailable = false;
            //print("Path not available");
        }
    }

    bool CalculateNewPath()
    {
        agent.CalculatePath(toGo.transform.position, navMeshPath);
        print("New path calculated");
        if (navMeshPath.status != NavMeshPathStatus.PathComplete)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

}

Make contact!

Did you like this content? Let's talk...

I'm a game developer, I use unity. If you want to develop something, tell me!