0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

My reason is,I am trying to display the photos of all employees in my company with respect to their employee id. so the best practise is to call from resources by passing the employee id no?
//Load a Texture (Assets/Resources/Textures/texture01.png) var texture = Resources.Load<Texture2D>("Textures/texture01"); You could try this approach, just remember to name the pictures right and assign in place of the "texture01"
but since I am showing a photo,shouldnt it be a sprite? I am new to unity so please forgive me the question sounds stupid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.