exe2k
February 19, 2022, 4:15am
1
If i select 2 or more objects in Hierarchy the script executes each time;
How to execute it just once in case of multiple selection?
public class MyClass : EditorWindow
{
#if (UNITY_EDITOR)
[MenuItem("GameObject/Make it Cool")]
static void CreatePrefab()
{
GameObject selected = null;
selected = Selection.activeGameObject;
if(selected){
//some cool(not) code here
}
Selection.activeGameObject = null; //nope
Selection.objects = null; //also didn't help
Debug.Log("Executed"); //3 objects selected - 3 "Executed" printed out in Console :-(
}
#endif
}
So… I must “Clear” the Selection some how… Any help plz?
exe2k
February 19, 2022, 8:32am
2
Found out how to handle multiple objects, but I still have multiple execution of the script…
var selection = Selection.GetTransforms(SelectionMode.TopLevel);
var selection = Selection.GetTransforms(SelectionMode.TopLevel);
for (int i=0; i<selection.Length; i++)
{
Debug.Log(selection[i].name);
//do some work with each object here
}
exe2k
February 19, 2022, 9:12am
3
I came up with the solution, it’s fairly simple…and still a little dirty
Just added a check at the top to prevent duplicates to be created in case of multiple selection:
GameObject selected = Selection.activeGameObject;
var selection = Selection.GetTransforms(SelectionMode.TopLevel);
try
{
var wasAlreadyCreated = Selection.activeTransform.GetComponent<MyClass>();
if (wasAlreadyCreated) return;
}
catch {}