Help with sorting list by distance

Hi guys, before asking my question i searched for about an hour over internet and i didnt find any explanation of what is happening to my list. Here’s what i want to do : I want to sort my ennemies by their distance to my tower ( tower defense ). It works pretty well, my only problem is that my tower always attack the furthest of the list. Thanks if you can help me ! Thanks anyway if you cant ! :slight_smile:

if(targets.Count > 0) 
	{			
		targets.Sort(delegate(Transform t1, Transform t2)
	        { 
	        	return Vector3.Distance(t1.position, transform.position)
	              .CompareTo(Vector3.Distance(t2.position, transform.position));
	        }
		); 
        
		closestEnemy = targets[0];

This is due to CompareTo. You can either invert the distance ( Sort( delegate(…){ -D1.CompareTo(-D2); } )) or read the list from end to start instead of start to end, depending on what you do now.

By the way, you should compare the sqrMagnitude of the (t1.position - transform.position) to spare a square root, same for t2. Or even better, as I suspect the movements are 2D, compare (x1x1 + z1z1) to (x2x2 + z2z2).