The question is answered, right answer was accepted
[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#.
Answer by Tespy · Oct 04, 2018 at 07:45 PM
I've finally figured it out. If you want to use my solution, just get it off my Github: https://github.com/CG-Tespy/Unity-RectTransform-Preset-Utils
Absolutely amazing, thank you so much for this. Really makes working with Unity's UI so much less of a pain.
Glad to help. Should you find any bugs, be sure to let me know by creating an issue thread on Github :)
Answer by unidad2pete · Aug 20, 2017 at 09:55 PM
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:
I thought I was pretty clear with my question. :/ Oh, and I think I've already found a way to get the effect that I wanted. After I make sure it works as it should, I'll post it here.
Answer by hustlion-dev · Sep 29, 2018 at 04:05 AM
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.
Tested it on my end with non-stretch presets, and it didn't work. It even messed with the size of the UI element.