I have a button prefab that I'm instantiating like so:

GameObject button = Instantiate(Resources.Load("UI/Canvas/Button"), ReferenceToCanvasPanelRectTransform.transform) as GameObject;

This part works fine and the button is centered in the panel.

I would like to move the button a little bit though and lets say that the position of the button right now is (0, 0, 0).

If I get the button's RectTransform and attempt to move it like so:

RectTransform btn = button.GetComponent<RectTransform>();

btn.position = new Vector2(-20, 20);

it makes the button's position move to (-1051.05, 1149.5, -5679).

Why does it move so drastically and why does the Z position even change?

  • \$\begingroup\$ Did you mean to change its AnchoredPosition relative to its RectTransform parent? Just setting transform.position sets its worldspace position, which might be very different than the UI canvas's coordinate system. \$\endgroup\$
    – DMGregory
    Commented Dec 19, 2018 at 3:35

1 Answer 1


btn.position sets the absolute position in the world space coordinates, not canvas space. To move it on canvas, relative to anchor, use btn.anchoredPosition.

Also, CanvasScaler has an effect on how different world coordinates are from canvas coordinates.

Your CanvasPanel might be set not as ScreenOverlay but as rendered in world space and might even be not centered in the world (CanvasPanel.transform.position != Vector3.zero). That's why when you change the absolute position of btn it shows very different numbers.

If you want to change transform.position relative to current position, use transform.Translate(x, y, z) method. It moves the object by x, y, z coordinates from current position.

But for UI elements, stick with rectTransform.anchoredPosition. It makes your life so much easier...


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .