How do I change a UI element's Y position in code?

if someone can help me with this, I feel like I’ll understand the UI system a lot better.

I’ve got a scene like this:


I want to move that dialog to the top

in play mode, I discovered that that’s a Y pos of 840:

but this code moves it way above where it should be:

    public void MoveSayDialogToTop()
    {
        var sayDialog = GameObject.Find("SayDialog").transform.Find("Panel").GetComponent<RectTransform>();
        var pos = sayDialog.localPosition;
        sayDialog.localPosition = new Vector3(pos.x, 840, pos.z);
    }

When this is run, it looks like this in the scene:

It even has a different Y from what I’m setting, it has a 1440

What am I doing wrong?

Change localPosition too anchorPosition.

OK, that worked, but can you tell me WHY that worked?

Someone is asking a very similar question right here, but the answer for them is completely different: https://discussions.unity.com/t/548784

1 Like

localPosition is where the pivot of the element is in relation to the parents pivot.

anchorPosition is where the pivot of your element is in relation to your elements anchor.

Those can result in totally different things because every element (yours, and the parent) can have totally arbitrary values for pivot and anchor.
Your anchor can even be set to a “scaling anchor” so to say (which is when min and max are not equal, and your anchor describes a range instead of a point).

Take a look:

The second sentence is what you want to know:

In the end it totally depends on what you want to achieve.
Sometimes you want to deal with pivot, other times you want a delta to the anchor,
and yet other times you must use a non-point-anchor…

6 Likes

I’m sure this is in your answer and I can’t understand it: What does this have to do with positioning? I can take a Panel’s pivot and drag it around in the editor and the position doesn’t change at all. Why does changing anchorPosition change the position?

The editor works in a completely different way to make it “easier”.
When you are in the editor, and drag the pivot point around with your mouse, the unity editor basically counter-calculates how the “anchorPosition” would have to change so the rectangle visually doesn’t move. (same for anchor values etc).

That’s why there are the two buttons (raw mode, and blueprint mode).

Press raw mode to get no helper calculations or anything:

5 Likes

Thank you! That makes everything so much more clear! :slight_smile:

myPanel.GetComponent () .anchoredPosition = new Vector3 (-164, -124, 0);

1 Like

thanks for the code it helped :slight_smile:

1 Like