Change gameObjects parent at runtime

Hi all,

I have a script which at runtime moves a gameobject from one parent to another (from A to B).

 myobject.parent = ParentObject.transform;

And it works, but myobject has 2 child objects, which decouple after the move, so myobject and it’s children all become siblings, the hierarchy is not preserved.
How can i circumvent this? [so that when myobject changes parents, the children attached to myobject remain it’s children]

Illustration of what is happening if i wasn’t clear above.

Pre move:
-ParentA
--myobject
---myobject_child1
---myobject_child2

Post move:
-ParentB
--myobject
--myobject_child1
--myobject_child2

Only change the parent of the one object not its children. So don’t add / apply the script to the children objects.

Why do you iterate through the children ? If you want your Hierarchy to stay you only need to change the parent of “myobject”. Its children will follow.

So if i have :

-ParentA
 --myobject
 ---myobject_child1
 ---myobject_child2

And I want

-ParentB
 --myobject
 ---myobject_child1
 ---myobject_child2

I just do : myobject.transform.SetParent(ParentB)

But if i want to switch all ParentA children to ParentB and keep the hierachy under their children (Which I think is what you are trying to do) I do :

void TransferAllA2B(Transform a, Transform b){
		bool WorldPositionStayTheSame = false;

		Transform kid;
		while(kid = a.GetChild(0)){
			kid.SetParent(b,WorldPositionStayTheSame);
		}
	}

Now that i think about it, you error was to think that ‘GetComponentsInChildren()’ apply only to the children directly underneath, but no it goes recursively, and even worst : the first array element is the object on which you called the function.