【问题标题】:Gameobject Position Can't Follow Parent Position Unity游戏对象位置不能跟随父位置 Unity
【发布时间】:2017-02-26 01:31:20
【问题描述】:

将孩子的位置设置为父位置时遇到问题。

截图下方:

我的脚本:

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;

我把它放在更新中以确保位置没有改变。

为什么我的子位置不在内部并且与父位置相同,即使我已将其设置为与父位置相同的位置?

谢谢

丹尼斯

【问题讨论】:

  • 你的子对象Position是否设置为0?
  • No.. 当它设置为 0 时我在使用什么? .Localposition 还是 .position ?
  • 子游戏对象的变换组件上
  • 你必须使用 RectTransform。因为它们是 ui 对象。
  • @NahuelIanni 我设置了位置(0,0,0)位置被移动,但移动到屏幕的中心而不是父对象的中心。 EmreE,我已经给子组件设置了RectTransform。

标签: c# unity3d


【解决方案1】:

你需要改变这一行:

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

到这里:

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

或者这个:

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 方法,因为它是一个缓慢的方法。

【讨论】:

  • 我已经尝试过了。该位置已移动,但不在父中心位置内。所以我添加了这个 RightNext.transform.GetChild (0).GetComponent ().anchoredPosition3D = new Vector3 (0, 0, 0);这是有效的。请将此添加到答案中。我会勾选它。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 2020-01-03
相关资源
最近更新 更多