using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ScrollList_Script : MonoBehaviour {
public GameObject itemPrefab;
public int itemCount = 10, columnCount = 1;
void Awake () {
RectTransform rowRectTransform = itemPrefab.GetComponent<RectTransform>();
RectTransform containerRectTransform = gameObject.GetComponent<RectTransform>();
//calculate the width and height of each child item.
float width = containerRectTransform.rect.width / columnCount;
float ratio = width / rowRectTransform.rect.width;
float height = rowRectTransform.rect.height * ratio;
int rowCount = itemCount / columnCount;
if (itemCount % rowCount > 0)
rowCount++;
//adjust the height of the container so that it will just barely fit all its children
float scrollHeight = height * rowCount;
containerRectTransform.offsetMin = new Vector2(containerRectTransform.offsetMin.x, -scrollHeight / 2);
containerRectTransform.offsetMax = new Vector2(containerRectTransform.offsetMax.x, scrollHeight / 2);
int j = 0;
for (int i = 0; i < itemCount; i++)
{
//this is used instead of a double for loop because itemCount may not fit perfectly into the rows/columns
if (i % columnCount == 0)
j++;
//create a new item, name it, and set the parent
GameObject newItem = Instantiate(itemPrefab) as GameObject;
newItem.name = gameObject.name + " item at (" + i + "," + j + ")";
newItem.transform.parent = gameObject.transform;
//move and size the new item
RectTransform rectTransform = newItem.GetComponent<RectTransform>();
float x = -containerRectTransform.rect.width / 2 + width * (i % columnCount);
float y = containerRectTransform.rect.height / 2 - height * j;
rectTransform.offsetMin = new Vector2(x, y);
x = rectTransform.offsetMin.x + width;
y = rectTransform.offsetMin.y + height;
rectTransform.offsetMax = new Vector2(x, y);
}
}
}
Wouldn’t it be a bit easier (=less code)to use layout group functionalities? It seems you used the code from the splendid dynamic list youtube tutorial; I used that myself as well. At some point I noticed I could replace most of the code by using layout groups/elements which made the overall code much cleaner while retaining pretty much the same functionality.
It is strange looking and not finding anything on layouts.
Put simply though, you just need to add a “Vertical Layout Group” on your pnl_Content GO and it will automatically organise all the child elements within it’s RectTransform area.
By default it will stretch all children to layout uniformly in the area, if you don’t want that add LayoutElement components to each of the children and set their preferred height, then disable the “Force Child Expand” option on the group.
Hope this helps.
The layout groups are VERY easy to use to lay things out.
(Don’t forget to disable the script above :P)
Definitely need more “Best practices on coding in Unity” books @Adam-Buckner_1 , Talk to Will, he’ll get you plugged in.
My first title made a start, tag you’re it!