- Home /
(Unity 4.6 beta) Change UI Image source image from code? C#
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.
Answer by deadlyfingers · Jul 30, 2015 at 10:39 AM
If you have an Image sprite already set in Unity3D and you want to change it later you can use overrideSprite:
public void ChangeImage() {
// Sprite.Create params: Sprite.Create(Texture2D, Rect, Vector2d)
testImage.overrideSprite = Sprite.Create( Resources.Load<Texture2D>("newImage"), testImage.sprite.rect, testImage.sprite.pivot );
}
Answer by Kiwasi · Nov 26, 2014 at 11:04 PM
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);
}
Thanks Bored$$anonymous$$ormon! Now it says sprite not found when I type incorrectly! However when typed correctly I get this error message: "InvalidCastException: Cannot cast from source type to destination type. UnityEngine.Resources.Load[Sprite] (System.String path) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/BaseClass.cs:708)"
Is there something wrong with my pictures I have in my resources folder? They are both .jpg and .psd and noone works. What confuses me is that they dont seem to be sprites... but ins$$anonymous$$d they are textures? So dont I have to attach the texture to a sprite first before I can change sprite on my testImage?
$$anonymous$$y code shouldn't throw a casting error!
You can change from textures to sprites in the import settings. Just click on the picture and change the texture type to sprite.
Sprite is the 2D version of a texture.
Oh my god. Been searching for a solution to this problem for days. Thanks, bored.
Your answer
Follow this Question
Related Questions
How to load an image from file path? 1 Answer
Load level after Image Sequence 0 Answers
carrying player data from one scene to the next 1 Answer
load images in sequence into a gui? 2 Answers
Asyncchronous image loading 2 Answers