How can I position UI buttons in C#?
I am using a prefab UI Button to create several buttons during run-time in c#:
for (int i = 0; i < items.Count; i++) {
GameObject thumbnail = (GameObject)Instantiate(Resources.Load("InventoryItem"));
thumbnail.transform.SetParent (inventory.transform);
}
How can I set where on the screen the buttons are? I want them going across the bottom of the screen with a distance of 20 between each button.
Answer by KdRWaylander · Jan 05, 2016 at 09:03 AM
Hi,
Keep your code as it is right now, it's sufficient. What you need to do is to add a couple of components in your prefabs:
In your parent gameobject, add a Grid, Vertical or Horizontal Layout Group
Set the Padding at any value that you like (that's the space between the sides of the parent object and the beginning of your buttons)
Set the Spacing property to 20 (or any other value but 20 is what you asked)
Force expand if you want the buttons to adapt their size on the basis of how many button you add
Now in your button prefab, add a Layout Element
If you unchecked Force Expand in Width and/or in Height, set the Preferred Value to the size you want the buttons to have.
Now at runtime when you instantiate button prefabs with layout elements and set them as child of the parent with layout group Unity does the sizing and spacing for you :)