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,
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).


var enemies : Array;

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

function AddEnemy(){

Then when an enemy is killed you can use the RemoveAt function to remove it from the array and multiple turrets can share the same enemy array for targeting.

OK, I have solved my problem. I noticed that if Iremove the if part above and write `target = GameObject.FindWithTag("enemy").transform` in Update function it finds all the enemies with the tag.