Editor selection order

Is there a way to get the selection in the order that a user selected it? I’m really hoping I don’t have to track selections with any callbacks. It’s 2017 after all! I did see some other threads on this but they’re old and didn’t really have any good solutions.

As a simple example, renaming a selection of objects like this will do it in some other order. So I’ll get objects renamed as newName001, newName000, newName003, newName002, even though they were selected in sequence.

GameObject[] objs = Selection.gameObjects;

for (int i = 0; i < objs.Length; i++) {
    objs*.name = string.Concat("newName", i.ToString("000"));*

}

As far as I know, you should do a sort by transform.GetSiblingIndex()

Like:

public class UnityTransformSort: System.Collections.Generic.IComparer<GameObject>
{
   public int Compare(GameObject lhs, GameObject rhs)
    {
        if (lhs == rhs) return 0;
        if (lhs == null) return -1;
        if (rhs == null) return 1;
        return (lhs.transform.GetSiblingIndex() > rhs.transform.GetSiblingIndex()) ? 1 : -1;
    }
}

GameObject[] objs = Selection.gameObjects;
System.Array.Sort(objs. new UnityTransformSort());

No, as far as i know the editor does not track any order of your selection. The selection can be done in various ways where the order is not necessarily given. Also adding and removing items from a selection would make it difficult even for the user to determine the correct behaviour. Also “Selection.gameObjects” is already a filtered list as it only returns gameobjects. However the selection could include other items such as folders or other assets (I’, talking mainly about the project view).

If you want to implement a mass rename feature it would be the best to use an editor window or a wizard which the user opens and then select the objects in the order you want. This also allows a visual feedback and the reordering of the items in the wizard / editor window.

If you want to get the order of CTRL+CLICK, you may use Selection.objects instead of Selection.gameObjects and filter the object array by yourself.

Selection.objects is the actual unfiltered selection from the Scene.

Here is an example:

public static GameObject[] GetOrderedSelectedGameobjects()
{
    return Selection.objects.OfType<GameObject>().ToArray();
}