Working with localPosition and Anchor Points programmatically

I’m rendering a dynamic UI text list, so I can’t set anchor points/position through the editor.

I believe I have the correct code to achieve the same, but the result isn’t working as I expect.

I instantiate a Text prefab, assign the text, and set the anchor points:

rect.anchorMin =  new Vector2(1, 1);
rect.anchorMax =  new Vector2(1, 1);

This should anchor the text object to the upper right corner of the parent. These values are treated as “upper right” when done through editor.

To test, I set the localPosition to 0, 0, 0 - however the text appears in the center of my panel.

I must be misunderstanding one of these properties or missing another.

Don’t set localPosition if you want to work RectTransform-style. Instead, set anchoredPosition.

2 Likes

Can you clarify why that is? The anchoredPosition says it simply moves the pivot point of the rect, which doesn’t sound like it involves positioning the element.

The docs aren’t super clear, but why not try it yourself and see?

I did and it works, but that seems contradictory to the functionality documented.

Nevermind, I guess I was interpreting the docs differently. It’s not changing the pivot location, but it’s changing the location based on the pivot.

1 Like

Screw anchors altogether. They suck. Especially from code. :stuck_out_tongue:

I like to use the layout elements instead. Explicitly define empty RectTransforms where you need gaps.

If you do need anchors, set them up on a prefab, rather then messing with them in code.

I’ll take this rare opportunity to disagree with @Kiwasi on this one. The anchor points and anchoredPosition make pretty good sense to me, and I’ve successfully used them both in the editor and in code.

If you put the anchor min and max in the lower-left corner, then you can treat anchoredPosition as simply the old-fashioned “X and Y position of this object on the screen” (relative to its container, which is convenient).

But when you need to do something fancier, like make an object right-aligned or centered or whatever even as the container size changes, then the anchors make this pretty easy too.

Sure, it’s confusing at first… but believe me, it could be much worse. :slight_smile:

1 Like