I suspect there is a well-known and easy to explain reason for the behavior I'm seeing, but I am having difficulty explaining it (and likely not able to Google for the answer).
When adding a child
GameObject to a translated parent, the child's
localPosition is modified so that the child's
position stays the same after the parent's transformation is applied. Is there a way to not have this be the case?
In the following example, I create a parent object and move it to
(1,1,1), and then attach the child. I would like the child's position to be
(1,1,1), that is
(0,0,0) relative to the parent. However, the child's position is modified to be
(-1,-1,-1) so that it is
(0,0,0) relative to the world.
Here is a repro:
// Create parent. GameObject parent = new GameObject(); parent.name = "Parent GameObject"; parent.transform.parent = foregroundObject.transform; // Move the parent. parent.transform.Translate(1, 1, 1); // Add a child under the parent GameObject. GameObject child = (GameObject) GameObject.Instantiate(guildiePrefab); child.name = "Child GameObject"; child.transform.parent = parent.transform; // PROBLEM: localPosition is set so that the "global" position is (0,0,0). // How can I add the child object and have its position be (1,1,1)? this.Assert(child.transform.localPosition.ToString() == "(-1.0, -1.0, -1.0)"); this.Assert(child.transform.position.ToString() == "(0.0, 0.0, 0.0)");
Is there a different way I should be adding
child as a child of
parent? Or, should I always zero-out the position of
parent before adding a child? If that is the case, any reason why I need to do this? What is the rational for this design choice?