In the unity editor, it is possible to set the position based on anchor presets such as :
My goal is to be able to do this via code. The final result should position some buttons inside a parent panel element (one at top left, top right, center left, center right, bottom left, bottom right).
Now, I have managed to succeed partially by implementing a solution where I set anchorMin and anchorMax on the RectTransform as suggested in this post. Such as :
public static void SetAnchor(this RectTransform source, AnchorPresets allign)
{
source.anchoredPosition = new Vector3(0, 0, 0);
switch (allign)
{
case (AnchorPresets.TopLeft):
{
source.anchorMin = new Vector2(0, 1);
source.anchorMax = new Vector2(0, 1);
break;
}
...
However, when I run the code, I get something like this:
When I use the editor, everything is smooth as I want it to be :
I've researched the issue, but could only find a partial solution to the problem in these posts :
- Positioning UI elements with Anchor Presets via code
- https://answers.unity.com/questions/1007886/how-to-set-the-new-unity-ui-rect-transform-anchor.html
- https://answers.unity.com/questions/1225118/solution-set-ui-recttransform-anchor-presets-from.html?_ga=2.122772744.2075458563.1596501507-831037939.1592074428
Any idea on how to properly solve this would be greatly appreciated. :)