Sort list with non-anonymous delegate?

I never like anonymous functions. So instead of using an anonymous delegate :

Targets.Sort(delegate(Transform x, Transform y) {
			return Vector3.Distance(x.position, myTransform.position).CompareTo(Vector3.Distance(y.position, myTransform.position));
		});

Can’t you just use a something like this :

delegate int Comp(Transform t1, Transform t2);

	int Comparare(Transform t1, Transform t2){
	
		float d1, d2;

		d1 = Vector3.Distance (t1.position, myTransform.position);
		d2 = Vector3.Distance (t2.position, myTransform.position);
	

		return d1.CompareTo (d2);
	}


then where you need the sorting you make an instance of the delegate and pass it to the Sort: 

Comp compari = Comparare;
Targets.Sort(compari); ?

Clearly something is missing, but is it even possible? What is wrong?

List.Sort does not take a compare delegate. It takes an IComparer object to use to determine how to compare your objects.

So in your case you could create a TransformComparer, like so (not tested, but should work ok):

class TransformComparer : IComparer<Transform>
{
	public Transform myTransform;

	public int Compare(Transform x, Transform y)
	{
		return Vector3.Distance(x.position, myTransform.position).CompareTo(Vector3.Distance(y.position, myTransform.position));
	}
}

And then:

var comparer = new TransformComparer { myTransform = myTransform };
targets.Sort(comparer);

Also, I don’t get what you don’t like about anonymous methods… You don’t have to use the old C# delegate syntax that way, you could use lambda expressions (you don’t even need the curely braces nor the return statement if you had only one statement…)

So you could sort your targets in LINQ like so:

var orderdTargets = targets.OrderBy(t => Vector3.Distance(t.transform.position, myTransform.position));

Isn’t that sweet?

(See JK’s videos on lambdas if you’re not so familiar with them)

Look like you are on the right track.
When you ask what is wrong, what exactly is not working?

You might need to declare your compare function as static.