How to snap to the grid in the editor

Here’s a fun one. I am trying to make it so my characters that i drag out onto the map simply auto-snap to the Grid Graph under them. Here is the code from the editor script:

void OnSceneGUI()
{
	EntityInfo myTarget = (EntityInfo)target;
	switch (Event.current.type)
	{
	case EventType.MouseUp:
		if (Event.current.button == 0)
		{
			Debug.Log("Mouse Up! Detecting Tile");
			AstarPath.active = FindObjectOfType(typeof(AstarPath)) as AstarPath;
			NNInfo nnInfo = AstarPath.active.GetNearest (myTarget.transform.position);
			GraphNode aNode = nnInfo.node;

			if (aNode == null)
			{
				AstarPath.active = FindObjectOfType(typeof(AstarPath)) as AstarPath;
				AstarPath.active.Scan();
				nnInfo = AstarPath.active.GetNearest (myTarget.transform.position);
				aNode = nnInfo.node;
			}
			else
			{
				// Figure out what tile we're on.  Start by getting the base10 X,Z coordinates
				int x = (int)Mathf.Round (myTarget.transform.position.x);
				int z = (int)Mathf.Round (myTarget.transform.position.z);
				myTarget.transform.position = (Vector3)aNode.position;
			}
		}
	}
}

But - often times, somehow GetNearest() returns null, and rescanning does nothing. The only way to get the system to work is if i manually select the A* GameObject and manually re-scan the grid, even though it appears as if the grid had already been scanned. Any thoughts on this?

Try calling

AstarPath.active.SetUpReferences();

no luck. Am I going about this the right way?

Btw - some debug logs show that there is nothing wrong with AstarPath.active. It is setup correctly, it’s calling GetNearest() which returns a null node.

Hm. Hard to say.
And the position is close to the grid, right? (there is a max distance set in A* Inspector outside of which the GetNearest method will return null).

in that respect everything is fine. Remember - if i select the A* GameObject and scan, then try to move an object around, there are no issues. But every few minutes it loses those connections and i have to rescan.

Ah, probably the graph settings are not deserialized.

AstarPath.active.astarData.DeserializeGraphs();

boom! that did it, thanks!

1 Like