I need to change the source image (sprite) in my image script attached to my gameobject. Its easy to do manually by just draging an image from my resourses folder to the “source image slot” in inspector, but how do i do it in code? This is my atempt but it oly results in the image changing to just being white (the color i have chosed in inspector).
public Image testImage; // The one that is default when game starts
public void ChangeImage() {
testImage.sprite = Resources.Load ("newImage") as Sprite;
}
What is really odd is that it doesnt matter if I type “newImage” correctly…? Unity doesnt complain when it loads a non existing imgage in my resourses folder.
Unity returns null if the resource can’t be found. Casting using as will return null if the type is incorrect. An Image component with a null sprite renders white.
I would suggest using the generic version of Resources.Load. I would also suggest logging an error is this is null
Sprite newSprite = Resources.Load <Sprite>("newImage");
if (newSprite){
testImage.sprite = newSprite;
} else {
Debug.LogError("Sprite not found", this);
}