Exception when trying to add nodes to a PointGraph

I am dynamically generating points to add to a PointGraph. However, when I do so, It gives me the following error:

Exception: Trying to initialize a node when it is not safe to initialize any nodes. Must be done during a graph update AstarPath.InitializeNode (Pathfinding.GraphNode node) (at Assets/Resources/AstarPathfindingProject/Core/AstarPath.cs:1676) Pathfinding.GraphNode..ctor (.AstarPath astar) (at Assets/Resources/AstarPathfindingProject/Core/Nodes/GraphNode.cs:54) Pathfinding.PointNode..ctor (.AstarPath astar) Pathfinding.PointGraph.AddNode (Int3 position) (at Assets/Resources/AstarPathfindingProject/Generators/PointGenerator.cs:411) MapMaker.Start () (at Assets/Scripts/MapGenerator/MapMaker.cs:58)

The code that is calling it looks like this:
`
//code that creates Vector3[] waypoints - removed for readability

astarPath = GetComponent();
PointGraph navg = (PointGraph)astarPath.graphs[0];
foreach (Vector3 v in waypoints){//waypoints is a Vector3[] that is generated elsewhere
navg.AddNode((Int3)v);//this is line 58 - the one that’s throwing the error
}
`
This code is in the start function of a script attached to the same GameObject AstarPath is attached to.

When I searched for this error, I found arongranberg.com/vanillaforums/discussion/1084/exception-thrown-and-also-sometimes-crash-when-reloading-scene, which suggests looking at the script execution order. My script execution order is empty.

Hi

You need to do that inside a graph update. Like this

AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (delegate () { // Do stuff here }, null);

That code will now be called when it is safe to add nodes. Pathfinding threads will be paused. If this had not been done, pathfinding could be running in a separate thread while you were modifying the graphs, and that could cause all kinds of issues.

You could also do it right after scanning the graphs, like:
AstarPath.OnPostScan += delegate ( AstarPath ap ) { // Do stuff }; AstarPath.active.Scan ();

If you use the second approach, you might want to disable A* Inspector -> Settings -> Scan On Awake to avoid scanning the graphs twice (just removes some unnecessary overhead).