Get nearest object by using raycast

well I’m trying to use a get nearest object script to work with raycasting but its not quite working.

public Transform GetNearestTaggedMouseObject()
	{
		var nearestDistanceSqr = Mathf.Infinity;
    	var taggedGameObjects = GameObject.FindGameObjectsWithTag("waypoint"); 
    	Transform nearestObj2 = null;
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		//Debug.DrawRay (ray.origin, ray.direction * 20, Color.red);
			
			if (Physics.Raycast(ray, out hit, 20)) 
			{
				Vector3 destPoint = hit.point;
				
    			foreach (var obj in taggedGameObjects)
				{
        			var objectPos = obj.transform.position;
        			var distanceSqr = (objectPos - destPoint).sqrMagnitude;
					
        			if (distanceSqr < nearestDistanceSqr)
					{
            			nearestObj2 = obj.transform;
            			nearestDistanceSqr = distanceSqr;
        			}
				}
    		}
		if(Input.GetMouseButtonDown(0))
			moving2 = true;
		if(Vector3.Distance(transform.position, nearestObj2.transform.position) <= .1)
			moving2 = false;
		if(moving2 == true)
		{
			transform.LookAt(nearestObj2);
			transform.position = Vector3.MoveTowards(transform.position, nearestObj2.transform.position, Time.deltaTime);
		}
		return nearestObj2;
	}

This will make the controller move and follow the mouse cursor but not where you have clicked. I have also tried to put the raycast inside the if(Input.GetMouseButtonDown(0)) but it just made it so I had to hold down the mouse button for some reason. If there is a better way to do this without raycasting, I think I would rather do it that way but i haven’t found anything else yet.

I may be reading it wrong but i don’t think you’ll need raycasting for this.

Once you’ve got a waypoint you can just calculate the distance from your current point:

float distance = Vector3.Distance(transform.position, waypoint.transform.position);

You’ll need to go through all the waypoints and only keep the one with the shortest distance of course.

I would avoid using : foreach (var obj in taggedGameObjects) as even components are considered objects. (And may mean even more in javascript…)