Jerin Cherian
Jerin Cherian

Reputation: 436

How to set source image of an Image Object using code In Unity

I tried to change source image of an image Object in Unity from code.

I tried using resources.load but it returned none. How to do it properly?

Code I tried is

myImage.sprite = Resources.Load(newImageTitle);

This code doesn't go in my start function but on an onclick function of a button. I also tried as Sprite instead of

Upvotes: 0

Views: 2203

Answers (1)

Mika
Mika

Reputation: 66

Do you have a good reason to load from resources? If not, it's better to just cache the texture inside the class:

ImageChanger : MonoBehaviour.....
....

public Sprite NewSprite;

public void Change(){

var img = GetComponent<Image>();

img.sprite = NewSprite;

}
...

You can then drag this script onto the Button OnClickEvent

Upvotes: 2

Related Questions