How change target with GameObject.FindWithTag

I have a turret and should do:

-when see an enemy shoot, when he is out of range or dead(destroyed), turret must target next enemy.

But my script is doing:

-target first enemy and only target rest when first dead

function Update()
{

target = GameObject.FindWithTag("Enemy").transform;

     if(target && range)
     {

          var rotate = Quaternion.LookRotation(Objetivo.position - transform.position); 
          transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
 

          if (nextShotTime <= Time.time)
          {

              Shoot();
              nextShotTime = Time.time + timeBetweenShots;
          }
     }
}

I need turret target next enemy when 1st out of range

The FindWithTag command will only return the first object that Unity finds with that tag. It doesn’t take into account distance from the origin or any other object.

If you have to search by tags then use FindGameObjectsWithTag, this will return an array of objects, then simply add a check to find the first of those objects that is in range, or sort them by range first and pick the closest.

	var objs : GameObject[] = GameObject.FindGameObjectsWithTag("Respawn"); 
	for (var obj : GameObject in objs) {
		if (range) {
			target = obj.transform;
			break;
		}	
	}

Im trying this, but ‘objs’ is always empty :confused:

function Update()
{
	var objs : GameObject[] = GameObject.FindGameObjectsWithTag("Enemy");
	
	//Debug.Log(objs);
	
	for(var obj : GameObject in objs)
	{
		distance = (obj.position - tower.position).magnitude;
		if(distance<=range)
		{
			shootRange=true;
		}
		else
		{
			shootRange= false;

		}
	
		if(shootRange)
		{
			target = objs.transform;
			break;
		}
	}
}

From the YTChannel ‘Brackeys’.

public Transform target;
public GameObject[] enemies;
enemies = GameObject.FindGameObjectsWithTag("Zombie");
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach(GameObject obj in enemies) {
            
            distance = Vector3.Distance (obj.transform.position, this.transform.position);
            if(distance < shortestDistance){
                shortestDistance = distance;
                nearestEnemy = obj;
            }

            if(nearestEnemy != null && shortestDistance <= 9.0){
                target= nearestEnemy.transform;
            }
            
            
        }



//This is mine
//Look Enemy
if (target != null){
  Vector3 relativePos = objetivo.position - transform.position;
  Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
  transform.rotation = rotation;
}