- Home /
Parenting GameObject in the scene by scripts.
Hello everyone. I need your help on one thing that I can't properly find on the Unity API documentation.
I need to do this by scripting :
I already have the code to create an empty Gameobject, give then a name and component/scripts. And I can give then an order with the GameObject_B.transform.SetSiblingIndex(X); and it's work. But the GameObject_B.transform.SetParent(GameObject_A); don't work. In reality, my script create the Gameobject B and C on the same level. And I can't find the correct function to do this. Can you help me please ? Thank you very much :)
Answer by Dray · Nov 25, 2017 at 10:08 AM
You can do that with the game objects transforms:
GameObjectC.transform.parent = GameObjectB.transform;
Answer by Pogoda-Kotwica · Nov 25, 2017 at 10:11 AM
You need to point the exact transform. If you need to search through the hierarchy you can use (for example) Transform.Find or GetChild. There are multiple ways to do this but I think those two should be enough. So this should work in your case
GameObject_C.transform.SetParent(GameObject_A.GetChild(0))
Documentation https://docs.unity3d.com/ScriptReference/Transform.GetChild.html https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html