Tower defense, turret aiming wrong.

So, im making a TD game, and im trying to make the turret shoot at the closest enemy in a sphere collider, but instead it just shoots at the newest enemy to enter the sphere collider attached to the turret

Heres the code, mind you i havent added in little things like checking if the turret has a target yet and whatnot, mostly because ive been stuck on this for about a day and a half :\

var Target : GameObject;
var TargetList = new Array();
var DistanceVector : Vector3;
var TargetPos : Vector3;
var TurretPos : Vector3;
var ShortestDistance : float = 9999;
var Distance : float;

function Start () 
{
TurretPos = transform.position;
}

function Update () 
{
	
	FindEnemy();
	transform.LookAt(Target.transform.position);
}

function OnTriggerEnter (col : Collider)
{
	if (col.gameObject.tag == "Enemy")
	{	
			TargetList.Add(col.gameObject);
	}


}
function OnTriggerExit (col : Collider)
{
	if (col.gameObject.tag == "Enemy")
	{	
			TargetList.Remove(col.gameObject);
	}


}
function FindEnemy()
{
	for(i=0;i<TargetList.length;i++)
	{

		TargetPos = TargetList*.gameObject.transform.position;*
  •  DistanceVector = TargetPos - TurretPos;*
    
  •  Distance = DistanceVector.magnitude;*
    
  •  if(Distance < ShortestDistance)*
    
  •  {*
    

_ Target = TargetList*.gameObject;_
_
ShortestDistance = TargetPos.magnitude;*_

* }*

* }*
}

Hey

There’s a little bug on line 50:
ShortestDistance = TargetPos.magnitude;

Which should be:
ShortestDistance = Distance;

Also worth noting you’ve got a lot of variables there that are member variables but could just be local variables. For example: TargetPos, DistanceVector, Distance and ShortestDistance are only used inside FindEnemy. TurretPos is also just a copy of transform.position.

I’d be tempted to remove those variables from the class definition and just have something like:

function FindEnemy()
{
	var shortest_distance : float = float.MaxValue;

	for(i=0;i<TargetList.length;i++)
	{
 		var offset : Vector3;
		var target_pos : Vector3;
		var distance : float;

         target_pos = TargetList*.gameObject.transform.position;*

offset = target_pos - transform.position;
distance = offset.magnitude;
if(distance < shortest_distance)
{
_ Target = TargetList*.gameObject;_
shortest_distance = distance;
_
}*_

}
}
Basically minimizing my use of shared variables or duplication of data. Trying to stick to those rules really helps minimize bugs.
-Chris