Hello guys,
i want to build a list/table that visualizes different images and be able to scroll on them.
First of all, the c# code i have so far:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ScrollableList : MonoBehaviour
{
public GameObject itemPrefab; //this is the item that gets multiplied x times
public int itemCount = 10, columnCount = 1;
void Start()
{
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 + ")";
//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);
}
}
}
So basically i get a table with x columns ( = columnCount) that generated and displays a gameobject for every image i want to show.
I have 3 panels, e.g. the item_prefab panel and in there is a raw image.
This works quite fine with a dummy image. But now i am struggling to load different images in every gameobject.
→ The images (source) name should be from “1.png” to “x.png” where x = itemCount. They are all in a specific folder in my unity project. Can somebody help me on how to replace the dummy-image with the one i need ? (at this moment i am using a raw image in unity).