- Home /
Aligning UI Elements in Code
Hi,
So, I'm trying to create a menu with a variable number of buttons that display one below the other. To be more specific, I want the lower edge of each button to touch the upper edge of the next one. Due to scaling in the canvas and on the RectTransform for the button (and maybe other places?), I've been having difficulty actually making them align. My current (not working) code is:
for(int i = 0; i < numberOfButtons; i++) {
Vector3 newPos = mainCamera.WorldToScreenPoint(basePosition.position);
newPos.y -= i * buttonPrefab.GetComponent<RectTransform>().rect.height *
GetComponent<CanvasScaler>().scaleFactor;
newPos = mainCamera.ScreenToWorldPoint(newPos);
Instantiate(buttonPrefab, newPos, Quaternion.identity, transform)
}
And, for reference, base position is simply an empty RectTransform that's a child of the canvas, and is positioned in the top-left corner. My button prefab's pivot is also in its top left corner. This script is on the canvas object.
Any help would be much appreciated.
Your answer
Follow this Question
Related Questions
Find UI Image position in Screen Space 1 Answer
How can I find the scaled dimension of a RectTransform? 1 Answer
World BoxCollider size to Match Screen Space UI image size 1 Answer
UI element RectTransform WorldToScreenPoint issue 2 Answers
Which is better? Canvas Scaler or scaling transform 1 Answer