- Home /
Change parent of GameObject C#
So lets say I got 2 cubes
Cube1 and Cube2
I wan't to assign Cube1 as the Parent of Cube2, can anyone give a code example of how that is done?
Answer by Jake-L · Mar 29, 2011 at 10:45 AM
Sure,
Cube2.transform.parent=Cube1.transform
I tried looping through and adding all my asteroid game objects to a parent game object and they all appeared on top of each other. Not sure why this is happening tho.
have you tried to set the cube2 transform to a null first then add parent.
As this answer can be found on google: There is a SetParent method now. It keeps the local orientation. ScriptReference/Transform.SetParent.
I get the error "CS0103: The name `Cube1' does not exist in the current context"
How do I find Cube1?
Do not revive old, answered questions with comments like that. If you have a question, ask an actual seperate question. If you're new to Unity you may want to read the manual.
Note that while we usually try to do our best to answer any sort of questions around game development with Unity we can't really address basic program$$anonymous$$g questions. If you need more general help you should consider posting your question to the "help room" space of Unity answers.
@jordexciu the namespace "Cube1" was a example and is to be replaced with the gameobject of your chosing for ex: Insertyourothergameobjecthere.transform.parent = insertyourgameobjecthere.transform
Answer by mrmatt1877 · Dec 30, 2020 at 06:13 PM
parent = gameobject
keeps the worldposition
of the child while SetParent
allows you the choice between world position or changing the position to be relative to the parent.
'cube2.transform.SetParent(cube1.transform, true);
'cube2.transform.SetParent(cube1.transform, false);
'cube2.transform.parent = cube1.transform;
You can see a demonstration of how these will all parent the object but have different results on the position here https://www.monkeykidgc.com/2020/12/tips-and-tricks-unity-set-parent.html
Your answer
Follow this Question
Related Questions
Can one specify the parent of a gameobject in an array? 2 Answers
Make code effect children of a game object 1 Answer
Is there a way to make a selected object a child of another object during the game? 1 Answer
How to assign a game object with a raycast? 1 Answer
How can I attach a gameobject to another without changing its scale. 1 Answer