Hi guys. I have a quick question about RectTransforms.
I need to access the “Left” property in a UI Component FROM SCRIPT so I can shift it along a bit in certain situations. What’s the easiest/simplest way to do this? Is it a value that is inferred from other stuff, like the sizeDelta and the position, and if so, what is the best way to manipulate those to get that apparent change?
I know this is an old thread but I landed here in 2019 so I guess this is still valuable.
I just created a little script to answer your question.
Create a new script called RectTransformExtensions (or whatever you want), and put that in there:
public static class RectTransformExtensions
public static void SetLeft(this RectTransform rt, float left)
rt.offsetMin = new Vector2(left, rt.offsetMin.y);
public static void SetRight(this RectTransform rt, float right)
rt.offsetMax = new Vector2(-right, rt.offsetMax.y);
public static void SetTop(this RectTransform rt, float top)
rt.offsetMax = new Vector2(rt.offsetMax.x, -top);
public static void SetBottom(this RectTransform rt, float bottom)
rt.offsetMin = new Vector2(rt.offsetMin.x, bottom);
Now you can call these methods like this :
Hope this helps!
Actually, we cannot access the top, left, right, bottom individually as I know. so “Left”, “Right”, “Top” and “Bottom” of RectTransform properties so we have offsetMin and offsetMax which return a vector as follows
PanelSpacerRectTransform.offsetMin = new Vector2(0, 0); // new Vector2(left, bottom);
PanelSpacerRectTransform.offsetMax = new Vector2(-360, -0); // new Vector2(-right, -top);
The easiest and cleanest solution is to simply use RectTransform.SetInsetAndSizeFromParentEdge. See this page for more information : Unity - Scripting API: RectTransform.SetInsetAndSizeFromParentEdge
If you want your object to fill the entire space of the parent, just do this:
RectTransform rectTransform = gameObjectButton.GetComponent<RectTransform>();
rectTransform .SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, 0);
rectTransform .SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
rectTransform .SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
rectTransform .SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, 0, 0);
So combining stuff, I ended up doing this for my stretched RectTransforms:
private void PlaceRectTransform(RectTransform rectTransform, float left, float top)
RectTransform.Edge.Left, left, rectTransform.rect.width);
RectTransform.Edge.Top, top, rectTransform.rect.height);
Get the RectTransform of the stuf you want to move around anywhere you like, for example in
Start with a
And then you can do
PlaceRectTransform(rect1Down, 240, 860); where 240 and 860 are the same numbers you would type in the editor