Home Game Development Is there a way to display navmesh agent path in Unity?

Is there a way to display navmesh agent path in Unity?

0
Is there a way to display navmesh agent path in Unity?

[ad_1]

This is a really easy way to render the actual path of NavMeshAgents (but note that these Gizmos are only drawn in the Scene windows, not the actual Game window).

Use OnDrawGizmos!

It’s a really useful method you can fill out on any MonoBehaviour, and it gets called automatically, just like Start and Update, if it exists in your script.

private void OnDrawGizmos()
    {
        if (agent.destination != null)
        {
            Gizmos.color = Color.white;
            {
                // Draw lines joining each path corner
                Vector3[] pathCorners = agent.path.corners;
                
                for (int i = 0; i < pathCorners.Length - 1; i++)
                {
                    Gizmos.DrawLine(pathCorners[i], pathCorners[i + 1]);
                }

            }
        }
    }

Just make sure you provide a reference to your agent.

=====

Here’s some other examples of things you can do with OnDrawGizmos:

You can do things like:

  • draw a cube marker at the agent’s destination point.
  • draw a line from your agent to their destination.
private void OnDrawGizmos()
    {
        if (agent.destination != null)
            {
                Gizmos.color = Color.magenta;
                Gizmos.DrawCube(agent.destination, new Vector3(0.2f, 0.6f, 0.2f));
                Gizmos.DrawLine(agent.destination, transform.position + (Vector3.up * 1.5f));
            }
     }

What I like about it is that it’s very quick and easy to add, as you don’t need to deal with game objects or components. Just draw these things straight to the scene window without much fluffing around.

But again, if you want these things to appear in Game view, you’ll need to do something else!

[ad_2]