sort array of transforms by name

Hi,
I’ve been trying to sort a list of transforms by name in c# to no avail. I’ve read the ‘sort’ documentation, but I can’t get it to work. I also can’t get CompareTo to work in any way, even though i’ve added System.Collections.Generic.

I would greatly appreciate an example.

Thanks,
-Juanelo

I guess the easiest way is to use the Comparison<> version of Sort().

You just need to define a method that takes two references of the type you want to compare and that returns an integer.

The Comparison delegate:

public class Example : MonoBehaviour
{
    public List<Transform> myList;
    
    private static int CompareTransform(Transform A, Transform B)
    {
        return A.name.CompareTo(B.name);
    }
    public void SortList()
    {
        myList.Sort(CompareTransform);
    }
    [...]
}

That should do what you want, haven’t tested it …

I’ve seen the same issue. Bunny what you have is basically the same as:

using System.Linq;

_myList.Sort((x, y) => x.name.CompareTo(y.name));

However, this still does not seem to sort correctly. I have a list of transforms all named Tile_1, Tile_2, Tile_3, …

I still can get this to sort in order of 1, 2, 3, 4,…

What gives?