How to make Towers fire at multiple enemies?

I am making some kind of tower defence. The tower has a gun that locks to enemy and fires projectiles. It follows the enemy using Quaternion.LookRotation and Quaternion.Slerp and it works great. The problem is I copy the enemy many times by Instantiate. The tower kills the first enemy and does not lock on the rest.How can I make it follow every enemy? The relevant part of code:

``````var target : Transform;

if (target == null && GameObject.FindWithTag("enemy"))
target = GameObject.FindWithTag("enemy").transform;
var targetPoint = target.position;
var targetRotation = Quaternion.LookRotation (targetPoint - transform.position,
Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation,
Time.deltaTime * 20.0);
...

``````

While "FindWithTag" will find another enemy once the first is destroyed, you don't have much control over which enemy it finds.

Whereas what you probably want is for it to find the next nearest enemy.

You can do that with a bit of scripting, like this:

``````function GetNearestTaggedObject() : Transform {

var nearestDistanceSqr = Mathf.Infinity;
var taggedGameObjects = GameObject.FindGameObjectsWithTag("Enemy");
var nearestObj : Transform = null;

// loop through each tagged object, remembering nearest one found
for (var obj : GameObject in taggedGameObjects) {

var objectPos = obj.transform.position;
var distanceSqr = (objectPos - transform.position).sqrMagnitude;

if (distanceSqr < nearestDistanceSqr) {
nearestObj = obj.transform;
nearestDistanceSqr = distanceSqr;
}
}

return nearestObj;
}

``````

How about creating an array of enemies which you can add to as you instantiate new ones. This also means that the turret will target the enemies in the order that they were instantiated (unless you write a script to search through the array).

e.g.

``````var enemies : Array;

function Start(){
enemies = new Array();
}