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:
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.
GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph;
int width = 50;
int depth = 50;
float nodeSize = 1;
gg.center = new Vector3(10, 0, 0);
gg.SetDimensions(width, depth, nodeSize);
If you want to create a completely custom graph with your own nodes and connections you can use a point graph like this.
PointGraph graph = data.AddGraph(typeof(PointGraph)) as PointGraph;
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);
}));
Or you can create your own custom graph type, for more info about that take a look at Writing Graph Generators.
- See also
- Graph Types