PNG loaded from disk works in UI Image, but not in SpriteRenderer?
My game has the ability to load custom item graphics into buttons in the interface for the player's inventory at runtime. To do this, the game streams a .png file from disk into a bytearray, loads the bytearray into a texture, creates a new Sprite with that texture, and then slots the Sprite into the button image's sprite property, like so:
if( File.Exists( filePath ) ) {
byte[] bytes = File.ReadAllBytes( filePath );
Sprite currSprite = thisButton.GetComponent<Image>().sprite;
Texture2D tex = new Texture2D( currSprite.texture.width , currSprite.texture.height );
tex.LoadImage( bytes );
thisButton.GetComponent<Image>().sprite = Sprite.Create( tex , new Rect( 0 , 0 , tex.width , tex.height ) , currSprite.pivot );
}
So far, so good! However, I run into a weird problem when I try this same trick loading a PNG not into a button's image's sprite property, but rather, into the sprite property of a GameObject's SpriteRenderer component:
if( File.Exists( filePath ) ) {
byte[] bytes = File.ReadAllBytes( filePath );
Sprite currSprite = spriteRenderer.sprite;
Texture2D tex = new Texture2D( currSprite.texture.width , currSprite.texture.height );
tex.LoadImage( bytes );
spriteRenderer.sprite = Sprite.Create( tex , new Rect( 0 , 0 , tex.width , tex.height ) , currSprite.pivot );
}
This second block of code causes the game to load the PNG as a bytearray, and the resulting Sprite certainly isn't null, so you would expect that it worked--but the sprite just plain doesn't render when spriteRenderer.sprite is set to it.
As far as I can tell, I'm not doing anything meaningfully different from the code that works fine with UI images, and yet it doesn't work with the SpriteRenderer. I can't seem to figure out the issue. Is there some kind of weird limitation in Unity's SpriteRenderer component that I'm running up against here?
Your answer
Follow this Question
Related Questions
Loading textures without freezing at runtime 0 Answers
How can I take a screenshot, without saving it as a PNG, but to a tex2d? 1 Answer
Resize the Texture2D to fit the renderer size 0 Answers
resizing texturerect on update of animated 2D sprite 0 Answers
How do I get the Box Collidor to form around the shape of the Sprite? 2 Answers