pathfinding on water in unity in csharp

To enable pathfinding on water in Unity, you need to use Unity's built-in navigation system and set up your scene accordingly.

First, you need to set up Unity's Navigation Window by going to Window > AI > Navigation:

Navigation Window

Once you have the Navigation Window open, select the water surface in your scene and mark it as a NavMesh Obstacle component:

main.cs
NavMeshObstacle waterObstacle = gameObject.AddComponent<NavMeshObstacle>();
waterObstacle.carving = true; // Set to true to let the NavMesh generate around the obstacle.
waterObstacle.shape = NavMeshObstacleShape.Box; // Set the shape to a Box, Sphere, or Capsule.
265 chars
4 lines

After marking the water as an obstacle, you need to bake the NavMesh by clicking on the "Bake" button in the Navigation Window:

Navigation Window Bake Button

This will generate navigation nodes around the water surface so that your agents can navigate through it.

Finally, to have your agents navigate on the water surface using the NavMesh, you need to set their navigation type to "Car" and enable "Obstacle Avoidance" in their NavMesh Agent component:

main.cs
NavMeshAgent agent = gameObject.GetComponent<NavMeshAgent>();
agent.agentTypeID = NavMesh.GetSettingsByName("Car").agentTypeID; // Set the agent type to "Car" for water navigation.
agent.obstacleAvoidanceType = ObstacleAvoidanceType.NoObstacleAvoidance; // Set obstacle avoidance using "NoObstacleAvoidance" or "HighQualityObstacleAvoidance".
agent.speed = 5f; // Set the speed of the agent.
agent.angularSpeed = 120;
agent.acceleration = 8;
442 chars
7 lines

With these steps, you should now have your agents successfully navigating on water in Unity using the NavMesh system.

gistlibby LogSnag