How can I change a UI image from a large list of image files?

Hi there,

I’m very new to Unity UI and have a tricky problem I can’t figure out how to solve.

I have a Menu screen with an image in the center. On either side of the image are buttons pointing left and right, I need a way to change the current image in the center to the next image on a list when the right hand button is clicked and then be able to swap back when the left hand button is clicked etc. I’m not brilliant with CSharp yet but any help on how I may achieve this would be appreciated.

First you need to store your items in the resources folder. Be careful with this as it loads all these resources but I guess if you just want to show images then you’re gonna need them loaded anyway.

Highlight the Assets Folder right click and create Folder, call it Resources.

Drag you images in that folder.

Highlight them all and change to “Sprite 2D and UI”, you should be able to do all of them at once.

Then use this script, I’ve created a list that’s just got a few test images in it. You need to Add all your image names to that list (and replace mine).

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;

public class LoadNextImage : MonoBehaviour {

	public RectTransform ParentPanel;
	private List<string> ImageName;
	private int imageNum = 0;

	// Use this for initialization
	void Start () {
		ImageName = new List<string>();

		ImageName.Add ("AddComponent");
		ImageName.Add ("aisystem");
		ImageName.Add ("AnchorCorners");
		ImageName.Add ("antique_compass_rose_postcard");

		Debug.Log (ImageName.Count);
	}

	public void LoadNextPic(bool LeftRight)
	{
		if(LeftRight)	// right if true
		{
			imageNum ++;
			if (imageNum > ImageName.Count - 1)
				imageNum = 0;
		}
		else
		{
			imageNum --;
			if(imageNum < 0)
				imageNum = ImageName.Count - 1;
		}

		string tempName = ImageName[imageNum];

		Sprite mySprite =  Resources.Load <Sprite>(tempName);
		if (mySprite){
			ParentPanel.GetComponent<Image>().sprite = mySprite;
		} else {
			Debug.LogError("no sprite found ImageName = " + ImageName[imageNum]);
		}
	}
}

Create a new canvas and put a panel on there. Add a Next Button and a Previous button. Drag my script onto the panel then on the next button click + on the OnClick part in the inspector.

A slot appears and drag the panel with that script on it onto the slot, in the dropDown box to the right select LoadNextImage → LoadNextPic and tick the bool box that appears just below it.

Do exactly the same for the Previous button but don’t tick the box.

Apart from typos (bound to be some) you should be OK.

EDIT

Should have said the script holds a public reference for the panel so when you drag the script onto the panel then select the panel and drag it onto the ParentPanel slot in inspectors script section.