How to change Image sources through the Resources folder
Hey I simply want to be able to change one UI Image with another (in this example through pressing the spacebar).
But I'm not really sure how to do it properly. Would be nice if soembody could tell me what I'm doing wrong.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ImageTest : MonoBehaviour {
Image image;
private Sprite newImage;
void Awake () {
image = GetComponent<Image>();
newImage = Resources.Load <Sprite>("newImage1");
}
void Update (){
if(Input.GetKeyDown(KeyCode.Space)){
image.sprite = newImage;
}
}
}
Comment
Best Answer
Answer by shdes161 · Dec 12, 2015 at 12:21 AM
You have to use the overridesprite method in the Image component. Just make sure that the new image you are trying to change it to is loaded as a sprite.
And if you need to keep track of what image is being displayed, save it in a Hashtable with the object as the key and its current image as the value.
MyGameObject.GetComponent<Image>().overrideSprite = MyNewSprite;