Author Topic: Fix for Numeric Sorting of UIGrid / UITable Objects  (Read 4598 times)

DCalabrese

  • Newbie
  • *
  • Thank You
  • -Given: 2
  • -Receive: 0
  • Posts: 23
    • View Profile
Fix for Numeric Sorting of UIGrid / UITable Objects
« on: May 25, 2015, 05:22:18 PM »
In attempting to use the existing Alphabetic sort type to sort UIGrid / UITable lists to sort numeric entries, it does not seem to always reliably sort correctly. I had originally thought that the Alphabetic sort would work for numeric, but that does not seem to be the case. I've coded up a quick fix however that allows Smallest to Largest numeric sort:

In UITable.cs, line 26, change the enum to have a Numeric option:

  1.         public enum Sorting
  2.         {
  3.                 None,
  4.                 Alphabetic,
  5.                 Horizontal,
  6.                 Vertical,
  7.                 Custom,
  8.                 Numeric // Add this
  9.         }
  10.  

Still in UITable.cs, around line 128, add the following inside the "if (sorting != Sorting.none)" block:
  1.                         else if (sorting == Sorting.Numeric) list.Sort(UIGrid.SortNumeric);
  2.  

In UIGrid.cs, at the top where the Enum is for Sorting, add the Numeric option here as well:
  1.         public enum Sorting
  2.         {
  3.                 None,
  4.                 Alphabetic,
  5.                 Horizontal,
  6.                 Vertical,
  7.                 Custom,
  8.                 Numeric
  9.         }
  10.  

Finally, in UIGrid.cs, add the following around line 280, where the other sort methods exist:
  1. static public int SortNumeric (Transform a, Transform b) { return System.Convert.ToInt32(a.name).CompareTo(System.Convert.ToInt32(b.name)); }
  2.  

That's it! Now your numeric entries will for certain sort properly when you call Reposition. Hope it helps!

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Fix for Numeric Sorting of UIGrid / UITable Objects
« Reply #1 on: May 26, 2015, 03:07:08 PM »
Alphabetic sorting works fine, but it needs to be padded with zeroes like so:

001
002
003
..
010
011
..etc.

DCalabrese

  • Newbie
  • *
  • Thank You
  • -Given: 2
  • -Receive: 0
  • Posts: 23
    • View Profile
Re: Fix for Numeric Sorting of UIGrid / UITable Objects
« Reply #2 on: May 27, 2015, 03:12:16 PM »
I had tried adding the zeros but it wasn't reliably working. It would often group them like this:

001
010
011
002
020
003
030

I saw the same behavior with this too:
001
0010
0011
002
0020
0021

Etc.

I'm pretty certain this DID work in the past though, so I was a little surprised that it didn't now. However, I'm also running Unity 5, and I remember it working in Unity 4. So perhaps this is specifically a Unity 5 related issue.