[Solved] Setting position of rectTransform through anchor presets in code

When setting a rectTransform’s anchors through the anchor presets, you also get the option to set the position based on those anchors.

How do I replicate that functionality through code? I know how to replicate the anchor-setting functionality, but not the position-setting functionality.

If it helps any, I’m using Unity 5.0.0f4, and am coding in C#.

I’ve finally figured it out. If you want to use my solution, just get it off my Github: GitHub - CG-Tespy/Unity-RectTransform-Preset-Utils: Allows you to set the anchor presets in code, with the same results you'd get messing with the Rect Transform's inspector controls.

I dont know exactly what do you want to do, but here are some code I think you need to know:

GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
        GetComponent<RectTransform>().anchorMax = Vector2.zero;
        GetComponent<RectTransform>().anchorMin = Vector2.zero;
        GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 1);

values are vector2.zero, change like do you want.

And :

GetComponent<RectTransform>().rect.//more options

Check out:

Setting the offset seems to work for the position ( has the same effect as clicking the preset in the editor). The following code only tested with stretch presets (the bottom right one):

    GetComponent<RectTransform>().offsetMin = new Vector2(0, 0);
    GetComponent<RectTransform>().offsetMax = new Vector2(0, 0);

And this will make the Left, Top, Right, Bottom value of the rect transform to all be zero.

125323-qq截图20180929115956.png