Project Window Selection Order

I’m trying to make an editor script that will add the selected objects in the project window to an array.

Object[] selectedObjs = Selection.objects;

Now this works fine in the fact that it creates an array from my currently selected objects in my Project Window but I need the array to be in the same order as the objects appear in the project window hierarchy. Is there anyway to do this?

To sort the selection Alphanumerically (in the same way that the project window does) I made a simple comparer .

public class AlphaNumericSortUnityObject : IComparer<Object>
{
    public int Compare(Object lhs, Object rhs)
    {
        if (lhs == rhs) return 0;
        if (lhs == null) return -1;
        if (rhs == null) return 1;

        return EditorUtility.NaturalCompare(lhs.name, rhs.name);
    }
}

I then sort my list using the comparer

Object[] selectedObjs = Selection.objects;
Array.Sort(selectedObjects, new AlphaNumericSortUnityObject());

You’ll need to include the UnityEditor namespace to use the EditorUtility.NaturalCompare method in the comparer and you might want to include the comparer in an Editor folder as it won’t work in builds.