How do I change an UI image dynamically?

I am working on a Racing Game in which I need to show latest five ranks of each gameobject and for that I have to change the images at run time for which I am using UI images.
When I click on the object it shows the latest ranking but I want an UI images instead of a number.
Can anyone help me out?

Thanks in advance,
Shraddha

3 Answers

3

You can change image by setting your image via Image.sprite.

Thanks or the response :)

Create the public sprite object , like this;
public Sprite myImage;

Drop your sprite in editor.
where you want to change the image , find the object and access the component of Image and their variable of sprite and assign the my image to this. like this;

gameObject.GetComponent().sprite = myImage;

hope it help you.

I was blank while I have very basic question,


How to set image from URL in Unity C#?


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

public class LoadWWW : MonoBehaviour {

	// Use this for initialization
	IEnumerator Start () {
		WWW www = new WWW("https://cdn.pixabay.com/photo/2013/07/12/19/16/spiral-154465_960_720.png");
		while (!www.isDone)
			yield return null;
		GameObject rawImage = GameObject.Find ("RawImage");
		rawImage.GetComponent<RawImage> ().texture = www.texture;
	}
}

I found this solution best for setting image. you can put values dynamically.