[C#] Problems with with List.Sort()

Hello guys!

I’m sure the solution of this problem will be pretty simple, but after a lot of research I just can’t make it work. I’m an amateur Unity/C# user, and I don’t quite understand what MSDN says ab

I have a list containing 3 different variables, and what I want to do is simply reorder it with descending “Speed” variable.

	public class ActionOrder:IComparer <ActionOrder> {
		
		public int CharacterCounter;
		public int Speed;
		public bool EnemyAction;
		
		public ActionOrder (int CharacterCounter, int Speed, bool EnemyAction){
			this.CharacterCounter = CharacterCounter;
			this.Speed = Speed;
			this.EnemyAction = EnemyAction;
		}

		public int Compare (ActionOrder a, ActionOrder b){
			if (a.Speed > b.Speed)
				return 1;
			else if (a.Speed < b.Speed)
				return -1;
			else return 0;
		}
	}

	public List<ActionOrder> actionOrder = new List<ActionOrder>();

	void Start (){

		Debug.Log (actionOrder[0].Speed);
		Debug.Log (actionOrder[1].Speed);
		Debug.Log (actionOrder[2].Speed);
		Debug.Log (actionOrder[3].Speed);

		actionOrder.Sort();
		
		Debug.Log (actionOrder[0].Speed);
		Debug.Log (actionOrder[1].Speed);
		Debug.Log (actionOrder[2].Speed);
		Debug.Log (actionOrder[3].Speed);

	}

This code results in this error, which I also couldn’t figure out what exactly it means:
“ArgumentException: does not implement right interface” and a giant log…

Also, if there’s a simpler method for sorting Lists I would appreciate if you share it.

Cheers!

IIRC the class needs to implement IComparable which has a CompareTo(T other) method in order for Sort with no arguments to work correctly. There is also an overload of Sort that takes a delegate in the event your class doesn’t implement that interface with the expectation that you mimic the interfaces functionality in that delegate.

I’m sorry, my knowlege is not good enough to understand what you’re saying…

You’re suggesting me to use IComparable instead of IComparer, is that it? I tried, but when I implemented “using System” it broke the rest of my code (mainly the "Random"s).

That seems…odd - but in any case you can just qualify that specific line if you want.

public class ActionOrder : System.IComparable<ActionOrder>
{
    public int CompareTo(ActionOrder other) { ... }
}

Yeah! That worked, thank you sir!