Changing a sprite on clicking a UI button.

Need help on creating a 2D dice. On clicking a button a random no must be generated (1-6) and depending upon the number the corresponding dice sprite must be displayed instead of the button or as a new image nearby. I’ve browsed though many questions like this and I’m not able to get it. Also, Under the Inspector menu for my button, I’ve set the transition to sprite swap and added the respective On Click() functions. Any help would be much appreciated. Here’s my code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class RandNumGen : MonoBehaviour {

	public int RandNum;
	public Sprite white1;
	public Sprite white2;
	public Sprite white3;
	public Sprite white4;
	public Sprite white5;
	public Sprite white6;
	//private int swcase;
	private SpriteRenderer sr;

	void Start () {
		sr = this.GetComponent<SpriteRenderer> ();


	// Use this for initialization
	public void StartX () {
		RandNum = Random.Range (1, 7);

	// Update is called once per frame
	public void UpdateX(){
		Debug.Log ("Generated Num :" + RandNum);
		ChangeSprite ();

	public void ChangeSprite(){

         switch (RandNum)
		case 1:
			sr.sprite = white1;
		case 2:
			sr.sprite = white2;
		case 3:
			sr.sprite = white3;
		case 4:
			sr.sprite = white4;

		case 5:
			sr.sprite = white5;
		case 6:
			sr.sprite = white6;

			Debug.Log("Not Working");


If this is your full code, it won’t work. You need to call StartX() from somewhere to generate your random number, at least from Start() if you want to do it once. Since you say that you do get the random number in the console, I assume you are already doing it.

Now the UpdateX() probably is your issue. You need to call it from somewhere after you generate your random, or from Update() if you want to constantly monitor for changes in the random for when you call StartX() again in your code.

Try renaming UpdateX() into Update() to test if it works, or make sure you call UpdateX() from your Update().

Also, make sure you have assigned the correct sprites to your “white” variables in the inspector.