Understanding the documentation when building a grid graph in runtime


I am new to Unity and have currently just brought pathfinding package with some experience in C#. I am building a grid graph in runtime. I have looked at the other questions in this forum about building a grid graph in runtime. But I felt that I am still needing more help. From the user questions I have discovered that I need to use Create Graph method. But I am not sure what other methods I need to use in order to set up a graph in runtime similar to the one in the getting started tutorial. I have a web developer background so coding games is new to me. How can I understand the documentation in order to know what I need to code to put together a grid graph?



Here is some code that should get you started. I haven’t actually tested it, but I think it would work well.

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

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

// Setup a grid graph with some values
gg.width = 50;
gg.depth = 50;
gg.nodeSize = 1;
gg.center = new Vector3 (10,0,0);

// Updates internal size from the above values

// Scans all graphs, do not call gg.Scan(), that is an internal method

Sorry for the late reply, I have been very busy. Thank you so much for this, this is more help that I could of expected.

Ah, I seem to have encountered a Null Reference Exception at line

AstarData data = AstarPath.active.astarData;

The property is static though so I should be able to access it like this? Is this a bug?


If you encounter a null ref there, then that would be because there is no AstarPath object in the scene, or it has not been initialized yet (e.g if you call it in Awake, your script might be initialized before the AstarPath script).


I’ve been trying to create a grid graph at runtime, and my code looks pretty much like the one you posted above (at least I’m glad I found out how to do that part by myself :p).

However, it doesn’t seem to do much. I don’t see any graphs added on the A* object, and nothing shows up in my scene either. What’s the best way to check if I’ve created a graph correctly ? Will it show up somewhere in the inspector / scene, or is that just for graphs created using the editor ?


Make sure you are not calling it in Awake, start should work.
It will probably fail if not called during play mode since when opening the inspector, the latest data will be deserialized and it will replace that graph. But since you said “runtime”, I guess this doesn’t apply.
I tested the code, and for me it works fine. It shows up in the editor and all.
If you have access, try the beta.

The problem was I think that I didnt add the pathfinding script as a component. I did this and it seemed to work.

AstarPath pathing = gameObject.AddComponent("AstarPath") as AstarPath;