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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

List Class Sort Usage

Discussion in 'Scripting' started by BradMick, Jan 21, 2017.

  1. BradMick

    BradMick

    Joined:
    Apr 2, 2014
    Posts:
    113
    Ran into a small problem. Trying to sort the planets my planet generator produces by their axis using the built in sort functions from the List class. This is my implementation. I came upon it while searching around on how to do it and this was the implementation I worked out. It seems that the sort gets caught in a loop...and without knowing enough about the how's and why's of it all I'm not smart enough to effectively troubleshoot it...which is why i'm here!

    Any insights or even a better way to tackle sorting my planets by their axis would be awesome!

    V/R

    Brad

    Code (CSharp):
    1. //Static class for the utility functions used by the program...
    2. public static class Utilities
    3. {
    4.     .....
    5.     public static int SortByAxis(PlanetNucleus p1, PlanetNucleus p2)
    6.     {
    7.         return p1.axis.CompareTo(p2.axis);
    8.     }
    9. }
    10.  
    11. //The sort call...
    12. planetArray.Sort(Utilities.SortByAxis);
     
  2. juicyz

    juicyz

    Joined:
    Jan 14, 2016
    Posts:
    85
  3. BradMick

    BradMick

    Joined:
    Apr 2, 2014
    Posts:
    113
    Yessir, planetArray is a PlanetNucleus and it's a List, sorry.

    private List<PlanetNucleus> planetArray = new List<PlanetNucleus>();

    that's the List object declaration. And then the axis values are floats.
     
  4. BradMick

    BradMick

    Joined:
    Apr 2, 2014
    Posts:
    113
    So as far as I can tell I've followed what's in the MSDN article...but the sort still isn't working...
     
  5. juicyz

    juicyz

    Joined:
    Jan 14, 2016
    Posts:
    85
    I think this is what you should do. I believe this will work (haven't tested the code)

    Code (csharp):
    1. public class PlanetNucleus : IComparable<PlanetNucleus> {
    2.    // Default comparer for PlanetNucleus type.
    3.    public int CompareTo(PlanetNucleus o)
    4.    {
    5.       // A null value means that this object is greater.
    6.       if (o == null)
    7.          return 1;
    8.       else
    9.          return this.axis.CompareTo(o.axis);
    10.    }
    11. }
    12.  
    13. // To use it:
    14. planetArray.Sort();