在setParent()之后更改UI RectTransform位置 [英] Change UI RectTransform position after setParent()
问题描述
我有这些行:
GameObject bp = Instantiate(MyPrefab);
bp.transform.SetParent(GameObject.FindGameObjectWithTag("ContentFactory").transform);
bp.transform.localPosition = new Vector3(0, 0, 0);
Si,我只是实例化一个预制件,我设置了一个父代,我想更改位置.
Si, I just instantiate a prefab, I set a parent and I want to change the position.
我的问题是,函数SetParent
为我的bp
GameObject设置了固定位置,此后我不知道如何更改此位置.最后一行什么也没改变....与.position
相同.
My problem is, the function SetParent
set a fixed position to my bp
GameObject, and after that I don't know how to change this position. The last line change nothing.... The same with .position
.
如何更改bp
的位置?谢谢!
How can I change the position of bp
? Thanks !
ContentFactory的检查器:
Inspector of ContentFactory :
bp的检查器:
层次结构(蓝色的内容为ContentFactory):
Hierarchy (Content in blue is ContentFactory) :
推荐答案
使用transform.localPosition
将使用它的相对位置.如果要更改世界空间中的位置,则需要使用transform.position
.
Using transform.localPosition
will use it relative position. If you want to change the position in world space, you need to use 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移动它.
This is a UI Object with a RectTransform
. You shouldn't move it with transform.position.
它应与:
bp.GetComponent<RectTransform>().anchoredPosition = ...
或
bp.GetComponent<RectTransform>().anchoredPosition3D = ...
请注意,使用RectTransform
时还有其他一些作用.
Note that there are other things that play role when using RectTransform
.
这包括anchorMax
和anchorMin
,可以使用以下方法进行修改:
This includes anchorMax
and anchorMin
which can be modified with:
bp.GetComponent<RectTransform>().anchorMax = ...
bp.GetComponent<RectTransform>().anchorMin = ...
这篇关于在setParent()之后更改UI RectTransform位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!