Creating graphs during runtime

How to create graphs during runtime from a script.

How to create graphs during runtime from a script.

If you for some reason cannot create the graph and set its settings during design time in the unity editor, it is possible to create graphs directly using scripting.

Note

Note that you can save and load both graph settings and complete scanned graphs from files. For more info about that see Saving and Loading Graphs. Usually you can define most of the settings in the unity editor, and then when the game starts only adjust a few values using a script and then re-scan the graph.

You can create a graph like this:

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

// This creates a Grid Graph
GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph;
The graph objects have all the settings that are exposed in the graph editor, so you can set them to any values you want, and then scan the graph.

// 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();
If you want to create a completely custom graph with your own nodes and connections you can use a point graph like this.

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

// This creates a Point Graph
PointGraph graph = data.AddGraph(typeof(PointGraph)) as PointGraph;

AstarPath.active.Scan(graph);

// Make sure we only modify the graph when all pathfinding threads are paused
AstarPath.active.AddWorkItem(new AstarWorkItem(ctx => {
// Add 2 nodes and connect them
var node1 = graph.AddNode((Int3) new Vector3(1, 2, 3));
var node2 = graph.AddNode((Int3) new Vector3(4, 5, 6));
var cost = (uint)(node2.position - node1.position).costMagnitude;
node1.AddConnection(node2, cost);
node2.AddConnection(node1, cost);
}));

// Run the above work item immediately
AstarPath.active.FlushWorkItems();

Or you can create your own custom graph type, for more info about that take a look at Writing Graph Generators.