How to get OverlapSphere to work correctly

Hi all.

I’m working on a project at the moment which is a turn-based strategy game on a hex grid, and having some trouble trying to find the closest hex to align buildings and such when trying to place them.

This is the code I have at the moment:

public IEnumerator AdjustBuildingPlacement (Vector3 pointA, Vector3 pointB, float time) {
		if(!isMoving) {
			isMoving = true;
			FindNearestTile();
			float t = 0f;
			while (t < 1f) {
				t += Time.deltaTime / time;
				transform.position = Vector3.Lerp(transform.position, nearest.position, t);
				yield return 0;
			}
			isMoving = false;
		}
	}

public Transform FindNearestTile() {
		Collider[] tilesNearby = Physics.OverlapSphere(transform.position, 0.5f);
		foreach (Collider hit in tilesNearby) {
			if (hit.tag == "HexTile") {
				Debug.DrawLine(transform.position, hit.transform.position, Color.red, 5);
				float dist = Vector3.Distance(transform.position, hit.transform.position);
				if (dist < minDist) {
					minDist = dist;
				}
			}
			nearest = hit.transform;
		}
		tilesNearby = null;
		return nearest;
	}

The problem is that the object moves to the closest hex tile in the negative x/z axes, even if there is a closer hex tile in the positive x/z axes. It should move to the closest hex tile regardless of direction, but it always moves to the closest hex tile downwards & left (negative on the x/z axes). I can see which is closer, and the Debug.DrawLine shows it clearly.

Hopefully somebody can help me with this!

Thanks in advance!

OK so I managed to solve the problem looking at some of the other answers here, and realized that the ‘minimum distance’ variable wasn’t being reset also. Here’s the working code if anybody needs it.

Note: The code runs when a specific key is pressed.

public IEnumerator AdjustBuildingPlacement (Vector3 pointA, Vector3 pointB, float time) {
    if(!isMoving) {
		isMoving = true;
		FindNearestTileV2();
		float t = 0f;
		while (t < 1f) {
			t += Time.deltaTime / time;
			transform.position = Vector3.Lerp(transform.position, nearest.position, t);
			yield return 0;
		}
		isMoving = false;
    }
}

public Transform FindNearestTileV2() {
	nearestDistanceSqr = Mathf.Infinity;
	Collider[] tilesNearby = Physics.OverlapSphere(transform.position, 1);
	foreach (Collider hit in tilesNearby) {
		if (hit.gameObject.layer == 8) {
			Vector3 objectPos = hit.transform.position;
			float distanceSqr = (objectPos - transform.position).sqrMagnitude;
			if (distanceSqr < nearestDistanceSqr) {
				nearestDistanceSqr = distanceSqr;
				nearest = hit.transform;
			}
		}
	}
	return nearest;
}