ClickToMoveController (Sample)

This is a very simple player controller that lets you click on the ground to move an agent. It demonstrates:

  • How to wait until a navmesh has been baked before enabling a NavMeshAgent.

  • How to subscribe to NavMeshBakerService.OnBakeCompleted.

  • How to issue movement commands via NavMeshAgent.SetDestination().

Inspector

  • Initialized (bool) Debug-only flag showing whether the script has been enabled after the first bake.

Behavior

  1. On Awake(), disables the attached NavMeshAgent.

  2. On Start(), subscribes to NavMeshBakerService.OnBakeCompleted.

  3. When the first bake finishes, it:

    • Sets initialized = true.

    • Enables the NavMeshAgent.

    • Unsubscribes from the bake event.

  4. On Update(), listens for a left mouse click:

    • Casts a ray from the camera to the clicked point.

    • If it hits geometry, sets that point as the agent’s destination.

Example Use

  1. Add a NavMeshAgent component to your Player GameObject.

  2. Add the ClickToMoveController script.

  3. Press Play, click around in the Scene, and watch the agent move.

This script is primarily a sanity check: it confirms that the runtime baking system is working and that NavMeshAgents can navigate on dynamically baked navmesh data.


Key Takeaways

  • Always wait for a navmesh to exist before enabling NavMeshAgents. Otherwise you may see warnings such as:

    Failed to create agent because there is no valid NavMesh
  • Use the OnBakeCompleted event for safe initialization of AI or player agents.

  • You can replace the input handling (mouse clicks) with your own control scheme — the important pattern is “wait for bake → enable agent.”

Last updated