- Home /
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[i].name = string.Concat("newName", i.ToString("000"));
}
Answer by Bunny83 · Jul 02, 2017 at 09:46 AM
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.
Oh no, not the answer I was hoping for! Oh well, thank you for the advice, much appreciated. Other softwares I use like $$anonymous$$aya or 3dsmax always return the selection with the order they were picked, so I was taken aback that it wasn't the case here. $$anonymous$$akes it more challenging to make tools!
Answer by Abaobao · Dec 14, 2017 at 09:28 AM
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());
Your answer
Follow this Question
Related Questions
How to get the top most GameObject selected in Editor 0 Answers
Editor Script Selection thinks Sprites are Texture2Ds. 2 Answers
Editor scripting, select a field 1 Answer
Select next object in Hierarchy? 0 Answers
Fold/unfold gameobject from code 4 Answers