How do I Iterate through child UI buttons to change their images?
So I'm working on a UI menu meant to hold a LOT of images, in order to avoid dropping performance when lots of images are loaded I'm trying to make them load in chunks. I've never used chunks before... or unity for that matter, but specifically the simplest way I could think of is to have a Vertical Layout Group instantiate prefabs containing a Grid Layout Group of 18 Buttons. My code instantiates the vertical layout group just fine but I don't know how to change the images or even text on the buttons. I had originally used a non chunk-based method to instantiate just the buttons in a group and with that code I could alter the text and images just fine but it's not working quite the same with this version so I'd like some insight on why.
Here's the code I'm currently using to instantiate the chunks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
public class ChunkInstantiate : MonoBehaviour
{
//Used to determine number of instantiated objects
public int objectNumber;
//Used to hold object prefab
public GameObject myPrefab;
//Used to parent prefab to canvas
private GameObject myObject;
public Transform myCanvas;
// Start is called before the first frame update
void Start()
{
Texture2D tex = Resources.Load("DisplayImages/sunset") as Texture2D;
Sprite newImage = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f));
Debug.Log(newImage);
for (int i = 0; i < objectNumber; i++)
{
myObject = Instantiate(myPrefab);
myObject.transform.SetParent(myCanvas);
myObject.transform.localScale = new Vector3(1, 1, 1);
myObject.GetComponentInChildren<Text>().text = Convert.ToString(i);
myObject.GetComponentInChildren<Image>().sprite = newImage;
}
}
Here's a rundown of the specific problems I'm facing. Most importantly is the images, they're completely ignored. I don't get any error messages but when I run the code
myObject.GetComponentInChildren<Image>().sprite = newImage;
Seems to have no effect on the outcome.
Less crucially but still important for figuring out what's going on, the code for generating text is having an effect but it only changes the text for the first button in every chunk. In other words the 1st button will be labeled "0" and then the 19th button will be labeled "1" etc. That code being:
myObject.GetComponentInChildren<Text>().text = Convert.ToString(i);
Any help would be much appreciated.
I still need help, but I've found something else out. The code that's meant to turn the buttons into images is working BUT it's been effecting the image that's meant to serve as the chunk rather than the buttons on the image.