UI Button and RectTransform via Prefab

I have a UI button prefab with the following rect transform properties:

Pos X 205, Top 26.5, Pos Z 0
Width 333, Bottom 1102.5

When I instantiate a button from this prefab it appears in the correct position…super…but

I need to loop through and instantiate more of the same button prefab and move them down the panel vertically with a small gap in between and this is where I am coming unstuck!

Here is how I am trying to do it, but I get a big narrowing smudge from top to bottom of screen?

// top starting position for loop
float t = 176.5f;

// bottom starting position for loop
float b = 884.5f;

// 1st button to appear at top
GameObject obj = Instantiate (buttonPrefab) asGameObject;

// parent the new button to the panel
obj.transform.SetParent (buttonContainer.transform, false);

// loop to create the required number of buttons
for (int x = 0; x < DataLoaderScript.buttonList.Length; x++) {

// object to store the new button
GameObject nObj;

// create a new button from prefab, this will sit on top of the already created button above
nObj = Instantiate (buttonPrefab) asGameObject;

// parent the new button to the panel
nObj.transform.SetParent (buttonContainer.transform, false);

// get the new buttons rect transform
RectTransform r = nObj.GetComponent();

// set the top
r.offsetMax = newVector2(r.offsetMax.x, t);

// set the bottom
r.offsetMin = newVector2(r.offsetMin.x, b);

// increment the top value
t += 138.0f;

// decrement the bottom value
b -= 137.5f;

Have you considered using a VerticalLayoutGroup to automatically arrange the items?

2 Likes

@Simie , perfect, lol did not know about these! Thanks :wink:

1 Like