using System;
using System.Collections.Generic;
using UnityEngine;
public class LearningScript : MonoBehaviour
{
List<SpeedOrgeniser> ListName = new List<SpeedOrgeniser>();
public class SpeedOrgeniser : IComparable<SpeedOrgeniser>
{
public string name;
public int combatSpeed;
public SpeedOrgeniser(string unit, int newCombatSpeed)
{
name = unit;
combatSpeed = newCombatSpeed;
}
public int CompareTo(SpeedOrgeniser other)
{
if (other ==null)
{
return 1;
}
Debug.Log(other.combatSpeed - combatSpeed);
return other.combatSpeed - combatSpeed;
}
}
void Start()
{
ListName.Add(new SpeedOrgeniser("player1", 150));
ListName.Add(new SpeedOrgeniser("player2", 121));
ListName.Add(new SpeedOrgeniser("player3", 121));
ListName.Add(new SpeedOrgeniser("player4", 123));
ListName.Sort();
foreach (SpeedOrgeniser item in ListName)
{
print(item.name + " " + item.combatSpeed);
}
}
}
What Confuses me is;
why did “-2” run twice?
why is it " positive 27" and not “-27”
what does “return 1” even mean? I have used “return” in loops before, but what does “return 1” do here?
I would love if you can explain to me step by step what is going on here. Many thanks
Player 1 - Player 2 = 29
Player 2 - Player 3 = 0
Player 2 - Player 4 = -2 (because Player 2 and 3 had same value, it moves again)
Player 3 - Player 4 = -2
Player 1 - Player 4 = 27 ( Not sure why this is not Player 4 - Player 1) Something to do with the return? Nop, the Return If Statement returns false anyway with this example
first it looks at the 2nd item and compares it to the 1st one, because the return value was positive that means it’s smaller and it shouldn’t go higher
then goes to 3rd and the return is 0 cause no difference between 2 and 3 so it stays in its place
then comes the 4th one and the value becomes negative (-2) so it should go higher, then it will compare it again with 2nd one so (-2) again and it will go higher
finally it will be smaller than the 1st one so it’s done
1st value does not need to be checked, other items move around it.
check for 121
121 - 150 = -29 so 121 goes higher
check for other 121
121 - 150 = -29 cause 150 is now in the 2nd place, and so 121 goes higher
121 - 121 = 0 done
check for 123
123 - 150 = -27 moves higher
123 - 121 = +2 so everything is sorted
btw if u want it reversed use
list.sort();
list.reverse();
don’t do it in compare