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 suit well to when you already have a grid based world. Features:

  • You can update the graph during runtime (good for e.g Tower Defence or RTS games)

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

  • Supports raycast and the funnel algorithm

  • Predictable pattern

  • Can apply penalty and walkability values from a supplied image

  • Perfect for terrain worlds since it can make areas unwalkable depending on the slope

The The Snap Size button snaps the internal size of the graph to exactly contain the current number of nodes, i.e not contain 100.3 nodes but exactly 100 nodes.
This will make the "center" coordinate more accurate.
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 a sphere obstacle in the scene and you want to update the grid where that sphere was instantiated, you can do this:
AstarPath.active.UpdateGraphs (ob.collider.bounds);
Where ob is the obstacle you just instantiated (a GameObject).
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 update that area and a small margin around it equal to collision testing diameter/2

See

Graph Updates during Runtime for more info about updating Graph Types during runtime

Hexagon graphs
The graph can be configured to work like a hexagon graph with some simple settings. Since 4.1.x 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 however that the 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
// 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

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

Inner Types

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

Public Methods

CalculateConnections (node)

Calculates the grid connections for a single node.

Public
CalculateConnections (x, z)

Calculates the grid connections for a single node.

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
CheckConnection (node, dir)

Returns if node is connected to it's neighbour in the specified direction.

Public
CountNodes ()

Number of nodes in the graph.

Public
ErodeWalkableArea ()

Erodes the walkable area.

Public
ErodeWalkableArea (xmin, zmin, xmax, zmax)

Erodes the walkable area.

Public
GetConnectionCost (dir)
Public
GetNearest (position, constraint, hint)

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

Public
GetNearestForce (position, constraint)

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

Public
GetNode (x, z)

Node in the specified cell.

Public
GetNodeConnection (node, dir)
Public
GetNodes (action)

Calls a delegate with all nodes in the graph.

Public
GetNodesInRegion (rect)

Get all nodes in a rectangle.

Public
GetNodesInRegion (shape)

All nodes inside the shape.

Public
GetNodesInRegion (bounds)

All nodes inside the bounding box.

Public
GetNodesInRegion (rect, buffer)

Get all nodes in a rectangle.

Public
GraphPointToWorld (x, z, height)

Transform a point in graph space to world space.

Public
GridGraph ()
Public
HasNodeConnection (node, dir)
Public
HasNodeConnection (index, x, z, dir)
Public
IsValidConnection (node1, node2)

Returns true if a connection between the adjacent nodes n1 and n2 is valid.

Public
Linecast (fromNode, toNode)

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

Public
Linecast (from, to)

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

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)

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

Public
OnDrawGizmos (gizmos, drawNodes)

Draw gizmos for the graph.

Public
RecalculateCell (x, z, resetPenalties=true, resetTags=true)

Recalculates single node in the graph.

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
SetNodeConnection (node, dir, value)
Public
SetUpOffsetsAndCosts ()

Sets up neighbourOffsets with the current settings.

Public
SnappedLinecast (from, to, hint, hit)

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

Public
UpdateTransform ()

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

Public

Public Static Methods

ConvertHexagonSizeToNodeSize (mode, value)
Public Static
ConvertNodeSizeToHexagonSize (mode, value)
Public Static

Public Variables

aspectRatio

Scaling of the graph along the X axis.

Public
center

Center point of the grid.

Public
collision

Settings on how to check for walkability and height.

Public
cutCorners

If disabled, will not cut corners on obstacles.

Public
Depth
Public
depth

Depth (height) of the grid in nodes.

Public
erodeIterations

Erosion of the graph.

Public
erosionFirstTag

Tag to start from when using tags for erosion.

Public
erosionUseTags

Use tags instead of walkability for erosion.

Public
getNearestForceOverlap

In GetNearestForce, determines how far to search after a valid node has been found.

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
isometricAngle

Angle to use for the isometric projection.

Public
LayerCount

Number of layers in the graph.

Public
maxClimb

The max position difference between two nodes to enable a connection.

Public
maxSlope

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

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
neighbourXOffsets

Offsets in the X direction for neighbour nodes.

Public Readonly
neighbourZOffsets

Offsets in the Z direction for neighbour nodes.

Public Readonly
nodes

All nodes in this graph.

Public
nodeSize

Size of one node in world units.

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
rotation

Rotation of the grid in degrees.

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
textureData

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

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
uniformWidthDepthGrid

This is placed here so generators inheriting from this one can override it and set it to false.

Public
useJumpPointSearch

Use jump point search to speed up pathfinding.

Public
width

Width of the grid in nodes.

Public
Width
Public

Inherited Public Members

active

Reference to the AstarPath object in the scene.

Public
drawGizmos

Enable to draw gizmos in the Unity scene view.

Public
GetNearest (position)

Returns the nearest node to a position.

Public
GetNearest (position, constraint)

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
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
Scan ()

Scan the graph.

Public

Private/Protected Members

CalculateAffectedRegions (o, originalRect, affectRect, physicsRect, willChangeWalkability, erosion)
Protected
CalculateDimensions (width, depth, nodeSize)

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

Private
CanUpdateAsync (o)
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
CrossMagnitude (a, b)

Magnitude of the cross product a x b.

Protected Static
DeserializeExtraInfo (ctx)

Deserializes graph type specific node data.

Protected
DestroyAllNodes ()

Destroys all nodes in the graph.

Protected
DrawUnwalkableNodes (size)
Protected
ErodeNode (node)

Internal method used for erosion.

Private
ErodeNodeWithTags (node, iteration)

Internal method used for erosion.

Private
ErodeNodeWithTagsInit (node)

Internal method used for erosion.

Private
ErosionAnyFalseConnections (baseNode)

True if the node has any blocked connections.

Protected
exists

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

Package
GetNodeConnection (index, x, z, dir)

Get the connecting node from the node at (x,z) in the specified direction.

Private
GetNodesInRegion (bounds, shape)

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

Protected
GetRectFromBounds (bounds)

A rect with all nodes that the bounds could touch.

Protected
hexagonNeighbourIndices

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

Package Static Readonly
OnDestroy ()

This function will be called when this graph is destroyed.

Protected
PostDeserialization (ctx)

Called after all deserialization has been done for all graphs.

Protected
RemoveGridGraphFromStatic ()
Private
ScanInternal ()

Internal method to scan the graph.

Protected
SerializeExtraInfo (ctx)

Serializes graph type specific node data.

Protected
UpdateArea (o)

Internal function to update an area of the graph.

Private
UpdateAreaInit (o)

May be called on the Unity thread before starting the update.

Private
UpdateAreaPost (o)

May be called on the Unity thread after executing the update.

Private
useRaycastNormal

Use heigh raycasting normal for max slope calculation.

Protected

Deprecated Members

CalculateConnections (node)

Calculates the grid connections for a single node.

Public Static
CalculateConnections (x, z, node)

Calculates the grid connections for a single node.

Public
DeserializeSettingsCompatibility (ctx)

An old format for serializing settings.

Protected
GenerateMatrix ()

Generates the matrix used for translating nodes from grid coordinates to world coordinates.

Public
GetNodesInArea (bounds)
Public
GetNodesInArea (shape)
Public
GetNodesInArea (bounds, shape)
Public
SetNodeConnection (index, x, z, dir, value)

Set if connection in the specified direction should be enabled.

Public
UpdateNodePositionCollision (node, x, z, resetPenalty=true)

Updates position, walkability and penalty for the node.

Public
UpdateSizeFromWidthDepth ()

Updates unclampedSize from width, depth and nodeSize values.

Public