Sort an array of classes by a variable value.

This is my class:

public class RareBlock

	{
		public string name;
		public Vector3 blocks;
		public int chance;
    }

I have an array of many instances of this class. How do I sort the array according to the value of chance?

Thanks

Use the Array.Sort() method that takes a Comparison:

Array.Sort(myRareBlockArray,
delegate(RareBlock x, RareBlock y) { return x.chance.CompareTo(y.chance); });

If anyone needs this in 2020, I created a function for a recent project, sorting and returning an array of custom classes, by first making it into a dictionary:

    public Dialogue[] SortDialogues(Dialogue[] _ds)
    {
        Dictionary<string, Dialogue> _dic = new Dictionary<string, Dialogue>();

        for (int i = 0; i < _ds.Length; i++)
            _dic.Add(_ds<em>.id + i, _ds*);*</em>

List keys = new List();
foreach (KeyValuePair<string, Dialogue> _d in _dic)
keys.Add(_d.Key);
keys.Sort();
List ds = new List();
foreach (string s in keys)
ds.Add(_dic~~);~~
return ds.ToArray();
}
Have fun with it! ^^
Greetings,
Max

Linq version, if you want that!

myArray = myArray.OrderBy( x => x.chance ).ToArray();

Here is the link to the documentation for having a compare method with array.sort. From there you can tell it what how to compare.

@joshpsawyer
I don’t mean to revive this conversation but its the only one remotely like my problem but i cant get it to work
I have a scriptable object called Potions which contains

`
    public string PotionName;
    public string PotionDescription;
    public int Cost
`

In another script i have an array which i want to sort

`
public Potions[] myPotions = new Potions[64];
`

i would like to sort this by the cost

i tried this

`
        Array.Sort(myPotions,
        delegate (Potions x, Potions y)
        { return x.Cost.CompareTo(y.Cost); });
`

i get this error.

NullReferenceException: Object reference not set to an instance of an object
BrothersManager.m__0 (.Potions x, .Potions y) (at Assets/New Game Manager/BrothersManager.cs:154)