在setParent()之后更改UI RectTransform位置

时间:2017-05-25 17:16:18

标签: c# unity3d position unity5

我有以下几行:

GameObject bp = Instantiate(MyPrefab);
bp.transform.SetParent(GameObject.FindGameObjectWithTag("ContentFactory").transform);
bp.transform.localPosition = new Vector3(0, 0, 0);

Si,我只是实例化一个预制件,我设置了父母,我想改变位置。

我的问题是,函数SetParent为我的bp GameObject设置了固定位置,之后我就不知道如何更改此位置。最后一行没有任何改变....与.position相同。

如何更改bp的位置?谢谢!

编辑:

ContentFactory的检查员:

enter image description here

bp的检查员:

enter image description here

层次结构(蓝色内容为ContentFactory):

enter image description here

2 个答案:

答案 0 :(得分:2)

使用transform.localPosition将使用它的相对位置。如果要更改世界空间中的位置,则需要使用transform.position

GameObject bp = Instantiate(MyPrefab);
bp.transform.SetParent(GameObject.FindGameObjectWithTag("ContentFactory").transform);
bp.transform.position = new Vector3(0, 0, 0);

修改

这是一个RectTransform的UI对象。你不应该用transform.position移动它。

应该移动:

bp.GetComponent<RectTransform>().anchoredPosition = ...

bp.GetComponent<RectTransform>().anchoredPosition3D = ...

请注意,使用RectTransform时还有其他一些因素可以发挥作用。

这包括anchorMaxanchorMin,可以修改:

bp.GetComponent<RectTransform>().anchorMax = ...
bp.GetComponent<RectTransform>().anchorMin = ...

答案 1 :(得分:0)

我将提供与程序员不同的答案,因为这是我使用新UI系统处理动态填充的ScrollViews的方式。我将不得不四处寻找,看看使用RectTransform.anchoredPosition是否效果更好。

我将锚定最小值:最大值设置为(0,1):(0,1),以便按钮(图像,文本等)将滚动视图的左上角视为原点。然后我也将枢轴设置为(0,1),这样按钮的左上角就是原点(然后这些值被烘焙到预制件中:我再也不需要再次使用它们了)。这让我可以将位置设置为(0,0,0)并将其放置在我想要的位置,虽然我通常会将它们向右和向下轻推几个像素以使其看起来很好,但所有项目都会收到相同的平面偏移。

RectTransform settings

然后in my code I can use .localPosition以允许这些值与我希望放置对象的位置对齐的方式,记住需要在旧项目下添加新项目,因此每个按钮的Y值是在第一个之后将变为负面。此偏移量将等于项目的高度(在检查器中可见)加上几个像素用于填充。

最后,我总是确保在ScrollView的内容的RectTransform上调用SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, totalHeight)来将滚动条更新为正确的值,并在必要时将内容转换的位置重置为(0,0,0),以便它滚动回到顶部。 totalHeight实际上是放置的下一个项目的(正)Y位置,再加上另一个平缓冲量(用于从顶部偏移内容的相同值),所以看起来好的。