Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

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

Discussion in 'Scripting' started by a847004, Mar 29, 2020.

  1. a847004

    a847004

    Joined:
    Mar 19, 2020
    Posts:
    4
    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;
    }
     
  2. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    488
    Please use code tags in the future:https://forum.unity.com/threads/using-code-tags-properly.143875/

    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.

    Code (CSharp):
    1. for (int i = 0; i < arrayLength; i++)
    2. {
    3.     for (int j = 0; j < arrayLength; j++)
    4.     {
    5.         // Compare them however you like here
    6.         if(array[i].maxHP < array[j].maxHP)
    7.         {
    8.             // Exchange two values
    9.             YouClass temp = array[i];
    10.             array[i] = array[j];
    11.             array[j] = temp;
    12.         }
    13.     }
    14. }
    This is called a bubble sort. It's not very good but it's something everyone starts with
     
    a847004 likes this.
  3. a847004

    a847004

    Joined:
    Mar 19, 2020
    Posts:
    4
    thank you very much!