- Home /
Simple editor script is creating an extra GameObject when using GameObject.Instantiate
Hello, I am trying to create a simple editor script to group selected objects together as children of a new empty object, it seems to work as inteded but with the side effect of creating an extra empty gameobject every time it runs and I cant figure out why, I added logs and a breakpoint to make sure it runs just once, and it does run just once but for some reason it keeps adding an empty gameobject.
This is the script:
[MenuItem("Tools/Group Objects Unparented &G")]
static void GroupObjectsUnparented()
{
GroupObjects(null);
}
[MenuItem("Tools/Group Objects Inside First Selected Object's Parent &#G")]
static void GroupObjectsParented()
{
GroupObjects(Selection.transforms[0].parent);
}
static void GroupObjects(Transform parent)
{
Transform[] selectedObjects = Selection.transforms;
GameObject groupParent = GameObject.Instantiate(new GameObject(), selectedObjects[0].position, Quaternion.identity, parent);
groupParent.name = "New Group Parent";
foreach(Transform t in selectedObjects)
{
t.parent = groupParent.transform;
}
}
It's not really game breaking since it's just an editor tool but it's definitly annoying and it's driving me crazy not understanding whats wrong with the script, so any help would be very appreciated. I'm using Unity LTS version 2019.4.23f1
Answer by Richie_V · Apr 02, 2021 at 08:09 PM
Ok, found the issue, new GameObject() already creates an empty game object in the scene so Instantiate just created a copy of the game object already in the scene, here is the working code.
static void GroupObjects(Transform parent)
{
Transform[] selectedObjects = Selection.transforms;
GameObject groupParent = new GameObject("New Group Parent");
groupParent.transform.position = selectedObjects[0].position;
groupParent.transform.parent = parent;
foreach (Transform t in selectedObjects)
{
t.parent = groupParent.transform;
}
}