Changing sprite at runtime causes it to stop resizing

So I’m changing the sprite on an Image component at runtime and this causes it to stop resizing with the Image’s RectTransform and just stays a fixed size. The code that changes the sprite (in Start()):

public Sprite mySprite;
 
GetComponent<Image>().sprite = mySprite

If I comment it out the image resizes fine so I know this is the problem.

Also, this exact code worked fine in Unity 4, but ever since I updated it won’t work.

You need to change your code to the following:

public Sprite mySprite;

void Start()
{
 mySprite = GetComponent<Image>().sprite;
}

The way you have it now, sets the sprite in the component to mySprite, you want to set mySprite to have the sprite from the component instead