Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UI RectTransform position

I have these lines :

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

Si, I just instantiate a prefab, I set a parent and I want to change the 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.

How can I change the position of bp ? Thanks !

Edit :

Inspector of ContentFactory :

enter image description here

Inspector of a bp :

enter image description here

Hierarchy (Content in blue is ContentFactory) :

enter image description here

like image 835
Clément Andraud Avatar asked Oct 19 '25 04:10

Clément Andraud


1 Answers

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);

EDIT:

This is a UI Object with a RectTransform. You shouldn't move it with transform.position.

It should be moved with:

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

or

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

Note that there are other things that play role when using RectTransform.

This includes anchorMax and anchorMin which can be modified with:

bp.GetComponent<RectTransform>().anchorMax = ...
bp.GetComponent<RectTransform>().anchorMin = ...
like image 70
Programmer Avatar answered Oct 21 '25 17:10

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!