uGUI keep position and size of GUI elements when anchors change

Hello.

In my script I have changed uGUI elements anchors by assigning new Vector2 for anchorMin and anchorMax to its RectTransform.

When change occurs, the position and size of GUI element changes.

How to make GUI keep its old position and size even if anchors changed?

In this code I’m changing anchor values:

RectTransform rect = (RectTransform) gameobject.transform;

rect.anchorMin = new Vector2(0f, rect.anchorMin.y);
rect.anchorMax = new Vector2(0f, rect.anchorMax.y);

After that, my UI elements changes its position and its width(It bacames zero).

5 and a half years later, I noticed that my earlier answer doesn’t work anymore (maybe because of the new Prefab Edit mode) so, I found a better way to do it, even without unnecessary Parent manipulations.

    public static void SetAnchors(this RectTransform This, Vector2 AnchorMin, Vector2 AnchorMax)
    {
        var OriginalPosition = This.localPosition;
        var OriginalSize = This.sizeDelta;

        This.anchorMin = AnchorMin;
        This.anchorMax = AnchorMax;

        This.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, OriginalSize.x);
        This.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, OriginalSize.y);
        This.localPosition = OriginalPosition;
    }

Old solution:

    public static void SetAnchors(this RectTransform This, Vector2 AnchorMin, Vector2 AnchorMax)
    {
        var Parent = This.parent;

        if (Parent) This.SetParent(null);

        This.anchorMin = AnchorMin;
        This.anchorMax = AnchorMax;

        if (Parent) This.SetParent(Parent);
    }

Also, this function might be handy: SetSizeWithCurrentAnchors()

Ok my guess is that you have initially all 4 anchors spread somewhere, then for no apparent reason you want to move them to the left side (the reason for which I asked and you haven’t answered). As people in comments below your question wrote - that’s a strange thing to want, but anyway I’ll try to answer how you can retain the width.

Example #1: Keep anchors respective to each other and move them left:

     rect.anchorMax = new Vector2(rect.anchorMax.x - rect.anchorMin.x, rect.anchorMax.y);
     rect.anchorMin = new Vector2(0f, rect.anchorMin.y);

Example #2: “Squash” the anchors to the left:

        float rrw = rect.rect.width;
        rect.anchorMin = new Vector2(0f, rect.anchorMin.y);
        rect.anchorMax = new Vector2(0f, rect.anchorMax.y);
        rect.sizeDelta = new Vector2(rrw, rect.sizeDelta.y);

If this is still not the thing that you want (for unexplained reason) then try to properly explain (quoting myself…):

which behavior of UI element you’re
trying to achieve?