I have a list of images that’s gathered from defeated enemies. It’s meant to hold their thumbnails so I can display them later like Rouge Legacy does after you finish a run.
The list is working and I can Debug.Log the image names saved in the List so it’s populated.
The part I’m having trouble with is then displaying them to the Unity UI system. I have a canvas setup and I placed 3 image elements in the canvas. I’ve also declared 3 variables to assign the images to.
My first question is what part of the GetComponent<> class do I use to assign these images to already created Image elements?
Second question, what would be involved in dynamically creating image elements sequentially so I don’t have to have a ton of prepared images just in case?
Creating UI elements from script
This will perfectly answer your last question. Basically, you can create a template of a single image and design it the way you want in the scene, then save it as a prefab. At runtime you instantiate a number of those prefabs and assign a new Image to them.
The call to assign a new image (called “sprite” in this case) to the Image component is this one:
UI Image sprite
In simple code it goes like this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class ChangeImage : MonoBehaviour
{
// Assign this with the prefab gameobject that has an Image component in the inspector.
// It already stores the Image component instead of a GO.
public Image imagePrefab;
// Fill your list with image somewhere.
List<Sprite> images = new List<Sprite>();
// For testing try this
// Remember to mark the image file as "Sprite UI" in the import settings in Unity
public Sprite testSprite;
void Start()
{
// Put test image in array or list
images.Add (testSprite);
// Instantiate the imagePrefab
Image imageInstance = Instantiate(imagePrefab);
// Set the parent to the Canvas or whatever UI element it needs to be.
// Place this script on that object or get a new reference instead of this.transform
imageInstance.transform.SetParent(this.transform, true);
// Assign the first image of the list or array or chose the one you need.
imageInstance.sprite = images[0];
}
}