Creating Sprites in code for use Dynamically.

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);
		}
	}

Okay so I got it to work by creating an entirely new Rect in the Sprite.Create() function rather than just copying the one I currently had.

I remember that I had done that in the first place but it didn’t work at the time. I must have fixed something else between those two times though I’m not sure what. Regardless it works now so that’s cool.

My guess for why the old Rect was breaking it is because instead of copying the rect I put into it, it must have made an entirely new one with a width and height of 0. Unity bug maybe? My own stupidity maybe? I’m not one to go back and find out.

Here’s the fixed portion of code:

public static void ChangeImageTexture(Image img, byte[] newImgData)
		{
			Texture2D OldTexture = img.sprite.texture;
			Texture2D newTexture = new Texture2D(OldTexture.width, OldTexture.height);

			newTexture.LoadImage(newImgData);
			
			img.sprite = Sprite.Create(newTexture, 
			                                new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0.5f,0.5f), img.sprite.pixelsPerUnit);

		}