2017-02-24 115 views
0

当把孩子的位置设置为父母位置时,我遇到了问题。Gameobject的位置不能跟随父位置Unity

下面的截图:

enter image description here

我的脚本:

RightNext.transform.GetChild (0).gameObject.transform.SetParent (TemporaryPage.transform,false); // TemporaryPage = Cherry Cake 

RightNext.transform.GetChild (0).GetComponent<RectTransform>().localScale = new Vector3 (1, 1, 1); 
      RightNext.transform.GetChild (0).gameObject.transform.parent = RightNext.transform; 
      RightNext.transform.GetChild (0).transform.position = RightNext.transform.position; 

,我把它更新,以确保该位置没有发生变化。

为什么我的孩子的位置不在父母的内部和相同的位置,即使我已经将父母的位置设置为相同的位置?

感谢

丹尼斯

+0

您的孩子对象位置是否设置为0? –

+0

没有..当它被设置为0我在用什么? .Localposition还是.position? –

+0

在儿童游戏物体的转换组件 –

回答

0

你需要改变这一行:

RightNext.transform.GetChild (0).transform.position = RightNext.transform.position; 

这样:

RightNext.transform.GetChild(0).GetComponent<RectTransform>().localPosition = Vector2.zero; 

OR这样的:

RightNext.transform.GetChild(0).GetComponent<RectTransform>().position = RightNext.transform.GetComponent<RectTransform>().position; 

在您的评论后编辑:我建议的两条线用于使子轴点与父轴点重合,我认为您需要这样做,并且不要始终将子对象轴放置在父对象的中心,无论的枢轴。

随着你的建议(你可以使用2D版本,因为我们与UI买卖)行:你把孩子支点在父对象的中心

RightNext.transform.GetChild(0).GetComponent<RectTransform>().anchoredPosition = Vector2.zero; 

,所以你需要设置孩子在(0.5,0.5)处旋转。但是,我强烈建议在Start方法中(或者在实例化一个新的孩子之后)获得对父代和子代的RectTransform的引用,以避免在Update内部持续使用GetComponent方法,因为这是一种缓慢的方法。

+0

我已经试过了。该位置已移动但不在父中心位置内。所以我添加这个RightNext.transform.GetChild(0).GetComponent ().anchoredPosition3D = new Vector3(0,0,0);这是行得通的。请将此添加到答案中。我会选中它。谢谢 –