r/unity • u/MalgorgioArhhnne • 3d ago
Coding Help Translating UI element behaves unexpectedly.
I attempted to translate a UI element using
backButton.Translate(0f, -10.4, 0f);The -10.4 is actually stored in a variable, I just changed it to a hardcoded value here to make it clearer. The UI element has a Pos Y of 14.4. After translation, it has a Pos Y of -45.02857. In the inspector, I subtracted 10.4 from the element's Pos Y and it became 4, as expected. Does anyone know why it behaves strangely when translating via script?
1
Upvotes
1
u/aquadolphitler 3d ago
Anchors maybe?
Try changing the anchored position directly instead of translation
1
u/johnv_dev 3d ago
Translate moves it in world units, not the Pos Y numbers you see in the inspector. the canvas is scaled, so 10.4 world units turns into a lot more than 10.4 in Pos Y. to move it the way the inspector does, change the anchored position instead, something like backButton.anchoredPosition += new Vector2(0f, -10.4f); with backButton as a RectTransform.