---
title: "Filter navmesh areas and traversal costs in C#"
url: https://recursiveai.org/onepath/cookbook/filter-navmesh-areas-and-costs/
description: "Exclude navmesh terrain or make it expensive in C# with OnePath query filters. Compare a water shortcut with a dry alternative in a runnable example."
version: "1.2.0"
---

# Filter navmesh areas and traversal costs in C#

**OnePath** is a free, open-source pathfinding library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OnePath) · [GitHub](https://github.com/recursive-ai-oss/onepath-csharp) · [Docs](https://recursiveai.org/onepath/docs/) · [Download example (.zip)](https://recursiveai.org/onepath/cookbook/filter-navmesh-areas-and-costs/filter-navmesh-areas-and-costs.zip)

A query filter controls which navmesh polygons a route may cross and how much travel through each terrain area costs.

```shell
dotnet add package RecursiveAI.OnePath
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

The snippet needs `routes.nav` from the zip; the full program below also creates it.

```csharp
using RecursiveAI.OneMath;
using RecursiveAI.OnePath;
using RecursiveAI.OnePath.Mesh;
using RecursiveAI.OnePath.Mesh.Queries;

// routes.nav is in the download.
var mesh = NavMeshSnapshot.Restore(
    File.ReadAllBytes("routes.nav"));
var query = new NavMeshQuery(mesh);
var filter = new QueryFilter()
    .WithAreaCost(1, 10);
var route = query.FindPath(
    new Vector3D(2, 0, 2),
    new Vector3D(6, 0, 2),
    new PathOptions { Filter = filter });
Console.WriteLine($"{route.Status}: {route.Cost:F2}");
```

```text
Found: 5.41
```

Unzip [the example](https://recursiveai.org/onepath/cookbook/filter-navmesh-areas-and-costs/filter-navmesh-areas-and-costs.zip), then `dotnet run`.

## The full program

The sample `routes.nav` is generated below from this layout. Each square is two units wide; the start is `(2,0,2)` and the goal is `(6,0,2)`.

```text
Z=3..5:   3 -- 4 -- 5    dry, area 0 / flag 1
Z=1..3:   0 -- 1 -- 2    middle: area 1 / flag 2
X ranges: 1..3, 3..5, 5..7
```

Polygon numbers are the assembly order in the program, not area IDs.

```csharp
using RecursiveAI.OneMath;
using RecursiveAI.OnePath;
using RecursiveAI.OnePath.Mesh;
using RecursiveAI.OnePath.Mesh.Queries;

// Six connected squares, side length 2. Area 1 / flag 2 marks water.
// Upper row: 3 -- 4 -- 5   (dry detour)
// Lower row: 0 -- 1 -- 2   (start, water, goal)
var settings = new NavMeshParams();
var vertices = new List<double>();
for (int z = 0; z <= 2; z++)
    for (int x = 0; x <= 3; x++)
        vertices.AddRange([1 + 2*x, 0, 1 + 2*z]);
var indices = new List<int>();
for (int z = 0; z < 2; z++)
    for (int x = 0; x < 3; x++)
    {
        int first = z*4+x;
        indices.AddRange([first, first+1, first+5, first+4]);
    }
var tile = NavTileAssembler.FromPolygons(settings, 0, 0, 0, 0,
    vertices.ToArray(), [4,4,4,4,4,4], indices.ToArray(),
    [0,1,0,0,0,0], [1,2,1,1,1,1]);
var mesh = new TiledNavMesh(settings);
var tileRef = mesh.AddTile(NavTile.Create(tile, settings));
File.WriteAllBytes("routes.nav", NavMeshSnapshot.Take(mesh));
var query = new NavMeshQuery(mesh);
var start = new Vector3D(2, 0, 2);
var end = new Vector3D(6, 0, 2);
foreach (var (name, filter) in new (string, QueryFilter)[] {
    ("ordinary", new()),
    ("expensive water", new QueryFilter().WithAreaCost(1, 10)),
    ("forbidden water", new QueryFilter { ExcludeFlags = 2 }) })
{
    var route = query.FindPath(start, end, new PathOptions { Filter = filter });
    var ids = route.Corridor.Select(poly =>
        Enumerable.Range(0, 6).Single(i => tileRef.Poly(i) == poly));
    Console.WriteLine($"{name}: {route.Status}, cost={route.Cost:F2}, polygons={string.Join(",", ids)}");
}
```

```text
ordinary: Found, cost=4.00, polygons=0,1,2
expensive water: Found, cost=5.41, polygons=0,3,4,5,2
forbidden water: Found, cost=5.41, polygons=0,3,4,5,2
```

With ordinary costs the route crosses water. Raising its multiplier selects the dry detour; rejecting its flag also selects that detour, but forbids water entirely. Check `route.Status`: a disconnected destination can produce a partial route rather than a complete path.

## Variations

To forbid polygons carrying flag 2 rather than make their area expensive, replace the filter in the snippet at the top:

```csharp
var filter = new QueryFilter { ExcludeFlags = 2 };
```

```text
Found: 5.41
```

To forbid an area by its area ID instead of a flag bit, replace the filter in the snippet at the top:

```csharp
var filter = new QueryFilter()
    .WithAreaCost(1, double.PositiveInfinity);
```

The remaining lines print:

```text
Found: 5.41
```

## Related recipes

- [Find nearby navmesh walls](https://recursiveai.org/onepath/cookbook/find-nearby-navmesh-walls/)
- [Find paths and raycast on a navmesh](https://recursiveai.org/onepath/cookbook/navmesh-queries/)

## The short answer

Pass a `QueryFilter` through `PathOptions.Filter`. Use `IncludeFlags` and `ExcludeFlags` to control polygon eligibility, and `WithAreaCost(area, multiplier)` to price an area. A finite high price is a preference; exclusion is a prohibition. The top snippet makes area 1 expensive without excluding it; the flag variation forbids it instead.

The full program separates these choices on one mesh. It builds six connected squares, marks the lower middle square as water, and compares ordinary travel, expensive water and forbidden water. All three routes reach the goal. Their printed polygon sequences show which corridor the search actually selected, rather than inferring a route from its final cost alone.

## How do area costs change a navmesh path?

Each polygon has an area ID. The filter assigns a multiplier to that ID, defaulting to one. OnePath prices a leg inside a polygon as its three-dimensional Euclidean distance multiplied by that polygon’s area cost. Its route search uses fixed crossing positions, including shared-edge midpoints—the centers of edges between neighboring polygons. The resulting corridor is then string-pulled: unnecessary turns are removed to produce straight-path points within the corridor.

That distinction matters when interpreting `Cost` and `Length`. The search cost is not simply the final smoothed path’s length times one global factor. Use the cost to understand search decisions and the returned points to move along the path. The example’s dry detour has a search cost of 5.41 when formatted to two decimal places; the number comes from this mesh’s crossing geometry, not a general cost for avoiding water.

Making water expensive does not guarantee a dry path. If every route crosses it, a finite multiplier still permits the crossing. A sufficiently short wet shortcut can also remain cheaper than a long dry detour. Choose a prohibition when crossing would be invalid, not merely undesirable.

## How do you exclude an area from a navmesh path?

Flag masks and area costs solve different problems. `ExcludeFlags = 2` rejects any polygon carrying that bit. `IncludeFlags` normally requires at least one matching bit; its default `0xFFFF` accepts even polygons whose flags are zero. Exclusion still rejects matching polygons. A predicate is also available for policies that need to consider both flags and area IDs.

To prohibit an entire area by ID, assign positive infinity as in the variation. `WithAreaCost` returns a new filter; retain that returned value. Finite costs must be positive. Zero, negative and NaN costs are not valid substitutes for a blocked polygon.

Apply the same filter to any nearest-polygon or related queries that must share the character’s permissions. Off-mesh links are checked against their own flags and area as well as their target polygon. A route can therefore fail even when its destination polygon itself is allowed.

Finally, a terrain label must exist on the navmesh, not just on a source grid. The 2D grid builder carries over wall versus non-wall, not the grid’s area IDs or multipliers. This example uses `NavTileAssembler.FromPolygons` to assign areas and flags explicitly. See [navmesh queries](https://recursiveai.org/onepath/docs/navmesh-queries/) for the cost model and [the tile format](https://recursiveai.org/onepath/docs/navmesh-format/) for stored polygon data.
