Click To Move (Sample)

Provided as a part of the Samples

Namespace: MegaCrush.NavmeshBaker.Sample


Purpose

A simple player controller that moves an agent to the clicked point on the ground — but only after the navmesh is ready. This prevents errors like:

“Resume can only be called on an active agent that has been placed on a NavMesh.”


How it works

  • Subscribes to BakerEvents.OnBakeCompleted.

  • On the first bake:

    • Enables the NavMeshAgent.

    • Warps the agent to a valid NavMesh point near its current position.

    • Unlocks input handling.

  • On each left mouse click:

    • Casts a ray into the scene.

    • Uses NavMesh.SamplePosition() to find the nearest walkable point.

    • Calls SetDestination() on the agent.


Inspector

  • Ray Distance (float) Max distance for the raycast from the camera.

  • Ray Mask (LayerMask) Which layers are valid for the click raycast.

  • Sample Radius (float) Radius around the click point to look for a valid NavMesh.

  • Verbose (bool) If enabled, prints debug logs when snapping and moving.


Example usage

  1. Ensure your scene has a BakerCoordinator with a NavMeshBakeProfile and Center Target.

  2. Add one or more DynamicNavMeshSurface components to define navigable regions.

  3. Create a capsule or character GameObject.

  4. Add a NavMeshAgent and this ClickToMoveController script.

  5. Play — after the first runtime bake, click anywhere on the ground to move the agent.


Why it’s useful

  • Ensures agents only start moving once the navmesh is valid.

  • Removes startup warnings/errors from spawning before a bake.

  • Demonstrates how to use BakerEvents.OnBakeCompleted to gate gameplay logic.


Script

Last updated