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.

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.

Try it:

GetComponent<RectTransform>().rect.height;