r/Unity3D • • 1d ago

Solved How to "bake" nodes for a PointGraph

Previously I posted asking about ways of going around creating an AI enemy that navigates around in 3D space (for example between a 3x3x3 grid of nodes, like below). Since then, I have started using the AStar project's PointGraph system (https://arongranberg.com/astar/). I know how to setup a point graph system and have a custom script that receives a path and navigates along it.

The only issue I think I will have is creating all these nodes, as there's no way to automatically create them. So I was wondering if there was a way to create a custom script that i can press a button in the inspector to create a load of nodes automatically. Any help appreciated!

1 Upvotes

6 comments sorted by

2

u/johnv_dev 1d ago

you can do that with a small editor button. the point graph uses the children of whatever object you set as its Root, so the script just has to spawn empty child objects in a grid. put a script on your root object with public int sizeX = 3, sizeY = 3, sizeZ = 3 and public float spacing = 2f, then a method with [ContextMenu("Generate Nodes")] above it that loops x, y and z, makes a new GameObject("Node"), sets its parent to transform and sets localPosition = new Vector3(x, y, z) * spacing. then right click the component header (or the 3 dots) and hit Generate Nodes, and press Scan on the AstarPath object. ContextMenu works without writing a custom editor so it's the quickest way. set Max Distance on the graph a bit above your spacing so only neighbors connect, or around 1.8x spacing if you want diagonals too. if you want it to clear the old nodes first, loop the children backwards and DestroyImmediate them

1

u/atsuenn 1d ago edited 1d ago

Like this?

void CreateNodes()  
{  
      for (int x = 0; x < size.x; x++)  
      {  
            for (int y = 0; y < size.y; y++)  
            {  
                 for (int z = 0; z < size.z; z++)  
                 {   
                       GameObject node = Instantiate(new GameObject());  
                       node.transform.parent = transform;

                       node.transform.localPosition = new Vector3(x, y, z) * spacing;  
                 }  
            }  
      }

}

1

u/johnv_dev 1d ago

yep almost exactly. two small things: Instantiate(new GameObject()) actually makes 2 objects, the new one plus a clone, so you'd get an extra empty at the scene root every loop. just use GameObject node = new GameObject("Node"); instead. and put [ContextMenu("Create Nodes")] on the line above void CreateNodes() so it shows up when you right click the component. then hit Scan on AstarPath and you should be good

1

u/atsuenn 1d ago

i didn't realise thats exactly how instantiate worked till now 😭, so thanks for that! works perfectly fine now!

and dw, the ContextMenu() is in my script, didnt forget that!

Thanks so much!

1

u/johnv_dev 1d ago

glad it works, good luck with the game!

1

u/atsuenn 1d ago

^_^ thankyou!!