Class GridGraph Extends NavGraph, IUpdatableGraph, ITransformedGraph, IRaycastableGraph

Public

Generates a grid of nodes.

The GridGraph does exactly what the name implies, generates nodes in a grid pattern.

Grid graphs are excellent for when you already have a grid-based world. But they also work well for free-form worlds.

Features:

  • Throw any scene at it, and with minimal configurations you can get a good graph from it.

  • Predictable pattern.

  • Grid graphs work well with penalties and tags.

  • You can update parts of the graph during runtime.

  • Graph updates are fast.

  • Scanning the graph is comparatively fast.

  • Supports linecasting.

  • Supports the funnel modifier.

  • Supports both 2D and 3D physics.

  • Supports isometric and hexagonal node layouts.

  • Can apply penalty and walkability values from a supplied image.

  • Perfect for terrains since it can make nodes walkable or unwalkable depending on the slope.

  • Only supports a single layer, but you can use a LayerGridGraph if you need more layers.

Inspector

Shape

Determines the layout of the grid graph inspector in the Unity Editor.

2D

Get or set if the graph should be in 2D mode.

Align to tilemap (grid)

Aligns this grid to a given tilemap or grid layout.

Width

Width of the grid in nodes.

Depth

Depth (height) of the grid in nodes.

Node size

Size of one node in world units.

Aspect ratio (isometric/advanced shape)

Scaling of the graph along the X axis.

Isometric angle (isometric/advanced shape)

Angle in degrees to use for the isometric projection.

Center

Center point of the grid in world space.

Rotation

Rotation of the grid in degrees.

Connections

Number of neighbours for each node.

Cut corners

If disabled, will not cut corners on obstacles.

Max step height

The max y coordinate difference between two nodes to enable a connection.

Account for slopes

Take the slope into account for maxStepHeight.

Max slope

The max slope in degrees for a node to be walkable.

Erosion iterations

Number of times to erode the graph.

Use 2D physics

Use Unity 2D Physics API.

Collision testing

Collider type

Collision shape to use.

Diameter

Diameter of capsule or sphere when checking for collision.

Height/length

Height of capsule or length of ray when checking for collision.

Offset

Height above the ground that collision checks should be done.

Obstacle layer mask

Layers to be treated as obstacles.

Preview

Shows the preview for the collision testing options.

Height testing

Ray length

The height to check from when checking height ('ray length' in the inspector).

Mask

Layers to be included in the height check.

Thick raycast

Toggles thick raycast.

Unwalkable when no ground

Make nodes unwalkable when no ground was found with the height raycast.

Rules
Take a look at Grid Graph Rules for a list of available rules.

Other settings

Show surface

Show the surface of the graph.

Show outline

Show an outline of the grid nodes in the Unity Editor.

Show connections

Show the connections between the grid nodes in the Unity Editor.

Initial penalty

Default penalty to apply to all nodes.

Updating the graph during runtime
Any graph which implements the IUpdatableGraph interface can be updated during runtime. For grid graphs this is a great feature since you can update only a small part of the grid without causing any lag like a complete rescan would.

If you for example just have instantiated an obstacle in the scene and you want to update the grid where that obstacle was instantiated, you can do this:

AstarPath.active.UpdateGraphs (obstacle.collider.bounds);
Where obstacle is the GameObject you just instantiated.

As you can see, the UpdateGraphs function takes a Bounds parameter and it will send an update call to all updateable graphs.

A grid graph will assume anything could have changed inside that bounding box, and recalculate all nodes that could possibly be affected. Thus it may end up updating a few more nodes than just those covered by the bounding box.

See

Graph Updates for more info about updating Graph Types during runtime

Hexagonal graphs
The graph can be configured to work like a hexagon graph with some simple settings. The grid graph has a Shape dropdown. If you set it to 'Hexagonal' the graph will behave as a hexagon graph. Often you may want to rotate the graph +45 or -45 degrees.

Note

Snapping to the closest node is not exactly as you would expect in a real hexagon graph, but it is close enough that you will likely not notice.

Configure using code
A grid graph can be added and configured completely at runtime via code.

// This holds all graph data
AstarData data = AstarPath.active.data;

// This creates a Grid Graph
GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph;

// Setup a grid graph with some values
int width = 50;
int depth = 50;
float nodeSize = 1;

gg.center = new Vector3(10, 0, 0);

// Updates internal size from the above values
gg.SetDimensions(width, depth, nodeSize);

// Scans all graphs
AstarPath.active.Scan();

Tree colliders
It seems that Unity will only generate tree colliders at runtime when the game is started. For this reason, the grid graph will not pick up tree colliders when outside of play mode but it will pick them up once the game starts. If it still does not pick them up make sure that the trees actually have colliders attached to them and that the tree prefabs are in the correct layer (the layer should be included in the 'Collision Testing' mask).

See

GraphCollision for documentation on the 'Height Testing' and 'Collision Testing' sections of the grid graph settings.

LayerGridGraph

Inner Types

Used for using a texture as a source for a grid graph.

Public Methods

AlignToTilemap (grid)

Aligns this grid to a given tilemap or grid layout.

Public
CalculateConnectionsForCellAndNeighbours (x, z)

Calculates the grid connections for a cell as well as its neighbours.

Public
CalculateTransform ()

Returns a new transform which transforms graph space to world space.

Public
CountNodes ()

Number of nodes in the graph.

Public
GetConnectionCost (dir)

Default cost of moving one node in a particular direction.

Public
GetNearest (position, constraint, maxDistanceSqr)

Nearest node to a position using the specified NNConstraint.

Public
GetNode (x, z)

Node in the specified cell.

Public
GetNodes (action)

Calls a delegate with all nodes in the graph.

Public
GetNodesInRegion (bounds)

All nodes inside the bounding box.

Public
GetNodesInRegion (shape)

All nodes inside the shape.

Public
GetNodesInRegion (rect)

Get all nodes in a rectangle.

Public
GetNodesInRegion (rect, buffer)

Get all nodes in a rectangle.

Public
GetRectFromBounds (bounds)

A rect that contains all nodes that the bounds could touch.

Public
GraphPointToWorld (x, z, height)

Transform a point in graph space to world space.

Public
IsInsideBounds (point)

True if the point is inside the bounding box of this graph.

Public
Linecast (from, to)

Returns if there is an obstacle between from and to on the graph.

Public
Linecast (from, to, hit, trace=null, filter=null)

Returns if there is an obstacle between from and to on the graph.

Public
Linecast (fromNode, toNode, filter=null)

Returns if there is an obstacle between the two nodes on the graph.

Public
Linecast (from, to, hit, trace=null, filter=null)

Returns if there is an obstacle between from and to on the graph.

Public
Linecast (fromNode, normalizedFromPoint, toNode, normalizedToPoint, hit, trace=null, filter=null, continuePastEnd=…)

Returns if there is an obstacle between the two nodes on the graph.

Public
Linecast (fromNode, fixedNormalizedFromPoint, toNode, fixedNormalizedToPoint, hit, trace=null, filter=null, continuePastEnd=…)

Returns if there is an obstacle between the two nodes on the graph.

Public
NearestNodeDistanceSqrLowerBound (position, constraint)

Lower bound on the squared distance from the given point to the closest node in this graph.

Public
OnDrawGizmos (gizmos, drawNodes, redrawScope)

Draw gizmos for the graph.

Public
RecalculateAllConnections ()

Recalculates node connections for all nodes in grid graph.

Public
RecalculateConnectionsInRegion (recalculateRect)

Recalculates node connections for all nodes in a given region of the grid.

Public
RelocateNodes (deltaMatrix)

Moves the nodes in this graph.

Public
RelocateNodes (center, rotation, nodeSize, aspectRatio=1, isometricAngle=0)

Relocate the grid graph using new settings.

Public
SetDimensions (width, depth, nodeSize)

Updates unclampedSize from width, depth and nodeSize values.

Public
SetGridShape (shape)

Changes the grid shape.

Public
SetUpOffsetsAndCosts ()

Sets up neighbourOffsets with the current settings.

Public
SetWalkability (walkability, rect)

Set walkability for multiple nodes at once.

Public
Snapshot (bounds)

Captures a snapshot of a part of the graph, to allow restoring it later.

Public
TranslateInDirection (dx, dz)

Moves the grid by a number of nodes.

Public
UpdateTransform ()

Updates the transform field which transforms graph space to world space.

Public

Public Static Methods

ConvertHexagonSizeToNodeSize (mode, value)

Converts a hexagon dimension to a node size.

Public Static
ConvertNodeSizeToHexagonSize (mode, value)

Converts an internal node size to a hexagon dimension.

Public Static
GetNeighbourDirections (neighbours)

Neighbour direction indices to use depending on how many neighbours each node should have.

Public Static

Public Variables

Depth
Public
LayerCount

Number of layers in the graph.

Public
MaxLayers
Public
Width
Public
aspectRatio

Scaling of the graph along the X axis.

Public
bounds

World bounding box for the graph.

Public
center

Center point of the grid in world space.

Public
collision

Settings on how to check for walkability and height.

Public
cutCorners

If disabled, will not cut corners on obstacles.

Public
depth

Depth (height) of the grid in nodes.

Public
erodeIterations

Number of times to erode the graph.

Public
erosionFirstTag

Tag to start from when using tags for erosion.

Public
erosionTagsPrecedenceMask

Bitmask for which tags can be overwritten by erosion tags.

Public
erosionUseTags

Use tags instead of walkability for erosion.

Public
inspectorGridMode

Determines the layout of the grid graph inspector in the Unity Editor.

Public
inspectorHexagonSizeMode

Determines how the size of each hexagon is set in the inspector.

Public
is2D

Get or set if the graph should be in 2D mode.

Public
isScanned
Public
isometricAngle

Angle in degrees to use for the isometric projection.

Public
maxSlope

The max slope in degrees for a node to be walkable.

Public
maxStepHeight

The max y coordinate difference between two nodes to enable a connection.

Public
maxStepUsesSlope

Take the slope into account for maxStepHeight.

Public
neighbourCosts

Costs to neighbour nodes.

Public Readonly
neighbourOffsets

Index offset to get neighbour nodes.

Public Readonly
neighbours

Number of neighbours for each node.

Public
nodeSize

Size of one node in world units.

Public
nodes

All nodes in this graph.

Public
rotation

Rotation of the grid in degrees.

Public
rules

Additional rules to use when scanning the grid graph.

Public
showMeshOutline

Show an outline of the grid nodes in the Unity Editor.

Public
showMeshSurface

Show the surface of the graph.

Public
showNodeConnections

Show the connections between the grid nodes in the Unity Editor.

Public
size

Size of the grid.

Public
transform

Determines how the graph transforms graph space to world space.

Public
unclampedSize

Size of the grid.

Public
uniformEdgeCosts

If true, all edge costs will be set to the same value.

Public
width

Width of the grid in nodes.

Public

Public Static Variables

StandardDimetricAngle

Commonly used value for isometricAngle.

Public Static Readonly
StandardIsometricAngle

Commonly used value for isometricAngle.

Public Static Readonly
neighbourXOffsets

Offsets in the X direction for neighbour nodes.

Public Static Readonly
neighbourZOffsets

Offsets in the Z direction for neighbour nodes.

Public Static Readonly

Public Enums

RecalculationMode
Public

Inherited Public Members

GetNearest (position, constraint=null)

Returns the nearest node to a position using the specified NNConstraint.

Public
GetNodes (action)

Calls a delegate with all nodes in the graph until the delegate returns false.

Public
Scan ()

Scan the graph.

Public
active

Reference to the AstarPath object in the scene.

Public
bounds

World bounding box for the graph.

Public
drawGizmos

Enable to draw gizmos in the Unity scene view.

Public
graphIndex

Index of the graph, used for identification purposes.

Public
guid

Used as an ID of the graph, considered to be unique.

Public
infoScreenOpen

Used in the editor to check if the info screen is open.

Public
initialPenalty

Default penalty to apply to all nodes.

Public
name

Name of the graph.

Public
open

Is the graph open in the editor.

Public
persistent

True if the graph will be included when serializing graph data.

Public
showInInspector

True if the graph should be visible in the editor.

Public

Private/Protected Members

AllocateNodesJob (size, dependency)
Protected
AssertSafeToUpdateGraph ()

Throws an exception if it is not safe to update internal graph data right now.

Protected
CalculateDimensions (width, depth, nodeSize)

Calculates the width/depth of the graph from unclampedSize and nodeSize.

Private
ClipLineSegmentToBounds (a, b, outA, outB)

Clips a line segment in graph space to the graph bounds.

Protected
CreateNavmeshSurfaceVisualization (nodes, nodeCount, helper)

Draw the surface as well as an outline of the grid graph.

Private
CrossMagnitude (a, b)

Magnitude of the cross product a x b.

Protected Static
DeserializeExtraInfo (ctx)

Deserializes graph type specific node data.

Protected
DeserializeNativeData (ctx, normalsSerialized)
Protected
DeserializeNodeSurfaceNormals (ctx, nodes, ignoreForCompatibility)
Protected
DestroyAllNodes ()

Destroys all nodes in the graph.

Protected
DirtyBounds (bounds)

Notifies the system that changes have been made inside these bounds.

Protected
DisposeUnmanagedData ()

Cleans up any unmanaged data that the graph has.

Protected
DrawUnwalkableNodes (gizmos, size, redrawScope)
Protected
FixedPrecisionScale
Private Static
GetNearestFromGraphSpace (positionGraphSpace)
Protected
GetNodesInRegion (bounds, shape)

All nodes inside the shape or if null, the bounding box.

Protected
HandleBackwardsCompatibility (ctx)
Private
HexagonConnectionMask

Mask based on hexagonNeighbourIndices.

Internal Static
OnDestroy ()

Function for cleaning up references.

Protected
PostDeserialization (ctx)

Called after all deserialization has been done for all graphs.

Protected
ScanInternal (async)

Internal method to scan the graph.

Protected
ScheduleGraphUpdates (graphUpdates)

Internal function to update the graph.

Private
SerializeExtraInfo (ctx)

Serializes graph type specific node data.

Protected
SerializeNodeSurfaceNormals (ctx)
Protected
allNeighbourIndices

Which neighbours are going to be used when neighbours=8.

Internal Static Readonly
axisAlignedNeighbourIndices

Which neighbours are going to be used when neighbours=4.

Internal Static Readonly
exists

True if the graph exists, false if it has been destroyed.

Internal
hexagonNeighbourIndices

Which neighbours are going to be used when neighbours=6.

Internal Static Readonly
newGridNodeDelegate

Delegate which creates and returns a single instance of the node type for this graph.

Protected
nodeData

Internal data for each node.

Protected
nodeDataRef
Internal
useRaycastNormal

Use heigh raycasting normal for max slope calculation.

Protected

Deprecated Members

CalculateConnections (node)

Calculates the grid connections for a single node.

Public
CalculateConnections (x, z)

Calculates the grid connections for a single node.

Public
Linecast (from, to, hint)

Returns if there is an obstacle between from and to on the graph.

Public
Linecast (from, to, hint, hit)

Returns if there is an obstacle between from and to on the graph.

Public
Linecast (from, to, hint, hit, trace, filter=null)

Returns if there is an obstacle between from and to on the graph.

Public
SnappedLinecast (from, to, hint, hit)

Returns if there is an obstacle between from and to on the graph.

Public
maxClimb

The max y coordinate difference between two nodes to enable a connection.

Public
penaltyAngle
Public
penaltyAngleFactor

How much penalty is applied depending on the slope of the terrain.

Public
penaltyAnglePower

How much extra to penalize very steep angles.

Public
penaltyPosition

Use position (y-coordinate) to calculate penalty.

Public
penaltyPositionFactor

Scale factor for penalty when calculating from position.

Public
penaltyPositionOffset

Offset for the position when calculating penalty.

Public
textureData

Holds settings for using a texture as source for a grid graph.

Public