How to sort array by using the value inside the classes?

Hello guys, I am new to both programming and unity. Therefore, I don’t know how to sort array by using the value I created in my customized class. For example, I am now planning to arrange the order of characters by comparing their speed inside their “status” classes. How can I do this?

public class Status : MonoBehaviour
{
public string charname;
public int maxHp;
public int hp;
public int maxMana;
public int mana;
public int attack;
public int defense;
public int speed;
}

Please use code tags in the future: Using code tags properly

Now, there are many ways to sort an array. You can do it manually, you can use the .Sort() or you can use Linq. I’ll just give you the simplest (and the least performant) solution right now.

for (int i = 0; i < arrayLength; i++)
{
    for (int j = 0; j < arrayLength; j++)
    {
        // Compare them however you like here
        if(array[i].maxHP < array[j].maxHP)
        {
            // Exchange two values
            YouClass temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}

This is called a bubble sort. It’s not very good but it’s something everyone starts with

1 Like

thank you very much!