I’m trying to make it so that the user can upload an image for their character portrait. I get the path for the image that they want to use and then I make a Texture2D load the image through a byte array.
Right now I’m just trying to make the UI Image object display the image. No matter what I do though it doesn’t seem to want to work. If I replace the texture of the sprite that already exists, it replaces all the instances of that sprite I’ve used. (It even permanently replaces the sprite texture in the editor) If I try to use the sprite.create method at all, it throws a “!hasError” and the sprite that loads onto the Image object is blank and not usable.
I’ve seen a few other posts who claim to have gotten it to work but with SpriteRenderer rather than Image and I’m not quite sure how those work with UI.
Any help is appreciated.
Here’s a code snippet:
public Image Portrait;
public void SetPortrait(string imgPath)
{
if(File.Exists(imgPath) && Path.GetExtension(imgPath).Equals(".png", System.StringComparison.InvariantCultureIgnoreCase))
{
byte[] fileData;
fileData = File.ReadAllBytes(imgPath);
Rect rct = Portrait.rectTransform.rect;
Texture2D OldTexture = Portrait.sprite.texture;
Portrait.sprite = Sprite.Create(new Texture2D(OldTexture.width, OldTexture.height),
new Rect(rct), new Vector2(0.5f,0.5f), Portrait.sprite.pixelsPerUnit);
Portrait.sprite.texture.LoadImage(fileData);
GetTemporaryCharacter().SetHashtableValue("Image", fileData);
}
}