- Home /
Cannot position child object relative to parent.
I created a parent game object at run time. Set it's position. Then, added another gameobject to it. I want the child game object to be @ (0,0) of the parent. Did some research but still can't make it work. Here is my code:
GameObject myParentObject = new GameObject();
myParentObject.transform.position = new Vector2 (-4.18f, -1.83f);
GameObject myChildObject = new GameObject();
myChildObject .transform.parent = myParentObject.transform;
A weird thing is I see the myChildObject nested as a child of the myParentObject, I click on it and it shows in the inspector the x=4.18 and y=1.83. Yes, they became positive values. Not sure why. All I want to do is create a parent object then create my first object @ (0,0) of that parent object by default. That's how flash/as3 handles things like these. I'm a bit confused.
Answer by Baste · Nov 26, 2014 at 01:03 PM
The position shown in the inspector of a child object is the child object's offset from the parent.
So if your parent object is at -4.18/-1.83, and the child object is at 0/0, the child object will show up in the inspector with the coordinates 4.18/1.83.
Setting a transform as a child of another transform does not move the child. It just ensures that the child moves and rotates with the parent. To make your child move to exactly the same position as the parent, you have to actually move it:
GameObject myChildObject = new GameObject();
myChildObject.transform.parent = myParentObject.transform;
myChildObject.transform.position = myParentObject.transform.position;
You can also use the localPosition value, which is the relative position with regards to the parent object:
GameObject myChildObject = new GameObject();
myChildObject.transform.parent = myParentObject.transform;
myChildObject.transform.localPosition = new Vector2(0,0);
Hope that helps!
Answer by smoi · Nov 26, 2014 at 01:22 PM
when you parent a child to a gameobject, it will keep the absolute postion by appling the inverse transform.
after parenting you probably want set: myChildObject.transform.localPosition = Vector3.zero;
At some part, my child object is moved wrongly.
I had to put this Vector.zero to the Update method.
Answer by popugames · Aug 17, 2018 at 08:37 PM
I found the best solution
just put this in your child script
private void Update()
{
if(transform.parent.position != transform.position)
transform.parent.position = transform.position;
transform.localPosition = Vector3.zero;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613172450im_/https://answers.unity.com/themes/thub/images/avi.jpg)