Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access RectTransform's left, right, top, bottom positions via code?

Tags:

I have a UI Canvas with render mode world space set. For all UI elements that belong to this canvas, I am seeing 'left', 'right', 'top' and 'bottom' variables in the RectTransform component in the editor. Any ways to access these variables via code?

like image 750
Sanath Bharadwaj Avatar asked Jun 11 '15 13:06

Sanath Bharadwaj


People also ask

How do I get anchor position in unity?

The Anchored Position is the position of the pivot of the RectTransform taking into consideration the anchor reference point. The anchor reference point is the position of the anchors. If the anchors are not together, Unity estimates the four anchor positions using the pivot placement as a reference.

How do I get rect transform position in unity?

click the highest level 3 dots for the whole window and select "Debug" You can now play with the object that has the RectTransform and see how the member variables in the debug window (which are the same variables accessible in script) show your changes.

What is RectTransform?

RectTransforms are used for GUI but can also be used for other things. It's used to store and manipulate the position, size, and anchoring of a rectangle and supports various forms of scaling based on a parent RectTransform.


2 Answers

Those would be

RectTransform rectTransform;  /*Left*/ rectTransform.offsetMin.x; /*Right*/ rectTransform.offsetMax.x; /*Top*/ rectTransform.offsetMax.y; /*Bottom*/ rectTransform.offsetMin.y; 
like image 180
maksymiuk Avatar answered Nov 03 '22 21:11

maksymiuk


RectTransform rt = GetComponent<RectTransform>(); float left   =  rt.offsetMin.x; float right  = -rt.offsetMax.x; float top    = -rt.offsetMax.y; float bottom =  rt.offsetMin.y; 

TL;DR

From the values displayed in the Inspector, my analysis is that Left, Right, Top and Bottom are positive if the corresponding bounds are in the rectangle shaped by the anchors of the RectTransform.

offsetMin.x as Left and offsetMin.y as Bottom always fulfill this assessment however offsetMax.x as Right and offsetMax.y as Top does not.

I simply took the opposite values of offsetMax to make it compliant (basic space modification).

like image 29
Numid Avatar answered Nov 03 '22 21:11

Numid