- Home /
[4.6 gui] Getting dimensions of 2D UI object (button for example)
I need to create few buttons in code and make them a neat grid. But I have no idea how I can get width or height of a button once I spawn them so it'll be a neat grid. I'm using new GUI for the job and don't know how to place them.
Here's code I have so far:
void Start () {
GameObject tempObject;
for (int i =0;i<maxCategoryNum;i++){
tempObject = Instantiate(CategoryButton) as GameObject;
tempObject.GetComponent<RectTransform>().parent = this;
tempObject.GetComponent<RectTransform>().position.x=0;
tempObject.GetComponent<RectTransform>().position.y=i*tempObject.GetComponent<RectTransform>().; //here should be height of the object
}
}
Unfortunately I have no idea how to get height of the object to place them correctly.
Answer by jenci1990 · Jan 25, 2015 at 05:48 PM
Try it:
GetComponent<RectTransform>().rect.height;
This solution only works if the anchors for the object in question overlap on Y (i.e., anchor$$anonymous$$in.y and anchor$$anonymous$$ax.y hold the same value). If anchor$$anonymous$$in.y and anchor$$anonymous$$ax.y are set to stretch the object vertically, reading rect.height is likely going to give you not only a wrong value but a negative value at that (it will hold something like the height of the object relative to its parent's height).
If anchor$$anonymous$$in and anchor$$anonymous$$ax are identical, then rect.width and rect.height will work. If they're not identical, then I don't know how to compute the width and height. I've been trying to get a simple answer to that for the last few hours. Searching for "Unity get object width" should help but everybody makes the same assumption that the anchors overlap.
Thanks desman, was wondering about that as well. This should not be the accepted answer :/
Answer by Teravisor · Jan 25, 2016 at 10:44 AM
The only solution I've found so far that includes both anchors and offsets in all cases is
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
And then manipulate their values to find what you need. For height it will be
float height = corners[2].y-corners[0].y;
If someone knows better solution that works in any case, that would be great.
I might be late but your answer helped me alot, I think your reply should be marked as correct answer.
Didn't work for me - for an element that takes roughly 1/5th of the screen the value got calculated as 4.43235 pixels...
GetWorldCorner
returns world coordinates. I'd guess your element was about 4.5 meters/units big. This is not returning pixels as far as I've found.
Your answer

Follow this Question
Related Questions
uGUI: Button that overlaps text 1 Answer
[4.6 UI] Buttons spawn from the bottom of the panel 1 Answer
[4.6 GUI] Resizing panel to fit it content 2 Answers
uGUI change depending on screen aspect ratio 0 Answers
Unity 4.6 New UI Button OnHoldPressed 0 Answers