Constantly looking for nearest object

Hello everyone. I have this script (attached to a moving character) that finds a nearest object (tower) and it works fine until the closest tower is passed by. The script does not recalculate the distance and only shows how far is the tower that was nearest after first calculation. I need the script to look for the nearest constantly and to change variable “closestTower” if closer tower is found. This is the part of my script (running in function Update()) that is responsible for finding nearest object:

        var towers : GameObject[];
		towers = GameObject.FindGameObjectsWithTag("Tower"); 
		var closestTower : GameObject; 
		var distance = Mathf.Infinity;
		
			for (var tower : GameObject in towers){
			
				var curDistance = (tower.transform.position - transform.position).magnitude;
				
				if(curDistance <= TowerNoticeRange && tower.collider.isTrigger == false){
			
					if (curDistance < distance) {
				
						closestTower = tower; 
				
						distance = curDistance;
					
					}
				
				}
				
			}

Where are you calling this? You’ll have to do the loop in Update().

use:
Vector3.Distance(transform.position, tower.transform.position)

The only thing I can imagine is that you define the variable distance outside of the Update function.
But this is just a guess since you didn’t post the complete code of the function.

Your logic is wrong. You are checking distance relative to the closest tower not the user or moving body. It works fine for the first time because curDistance < infinity . After the closest tower is reached you are replacing infinity with curDistance. Thus the tower should be closer than the distance between the user and the previous closest tower for the condition “if(curDistance < distance)” to be true, which is not going to happen unless curDistance is lesser than the previous curDistance.

Try going directly under the tower GameObject and it should work the second time.

Remove distance = curDistance and there is no need to check if curDistance is less than infinity as that will always be the case. Try this should work as you expect.