lookAt nearest object to another object

hi, i need a turret to look at the nearest object with a certain tag to another object. basically i’m making a sort of tower defence game where the enemies aren’t set to a track and i need the turrets to shoot the nearest enemy to the place that the user is attempting to protect, which can be a variable in this script. I only understand java so answers in java would be appreciated, thanks.

look forward to your answers :slight_smile:
oinkoinkflapflap

There’s lots of ways to do spacial look ups.
I recommend using Physics.OverlapSphere of the weapon range since this will use the built in spacial partitioning to do an efficient look up in your scene, then linearally searching through the results and figuring out which enemy is closest.

float nearest = Mathf.Infinity;
Collider nearestEnemy = null;

foreach(Collider enemyCollider in Physics.OverlapSphere(turretPosition, turretRange, enemyLayer))
{
   float distSqr = (enemyCollider.transform.position - turretPosition).sqrMagnitude;
   if( distSqr < nearest )
   {
       nearest = distSqr;
       nearestEnemy = enemyCollider;
   }
}

if( nearestEnemy )
    turretTransform.LookAt(nearestEnemy);