I’m using 2020.1.0f1 but I’m pretty sure this is in every version.
I have a gameObject Image with a sprite set in the editor, on play I change the sprite and call SetNativeSize so the sizeDelta will change to the new sprite dimensions.
unfortunately if the PPU of the sprite is anything other than 100 it will return the wrong sizeDelta. for example a sprite 48x48, with a PPU of 1 will get a sizeDelta of 4800x4800.
The two solutions around this is either manually setting the sizeDelta using the image.sprite.bounds.size myself, or delaying SetNativeSize for a frame.
using UnityEngine;
using UnityEngine.UI;
public class ImageChanger : MonoBehaviour
{
[SerializeField] Image image = default;
[SerializeField] Sprite sprite = default;
void OnEnable()
{
image.sprite = sprite;
// incorrect result if ppu is not 100
image.SetNativeSize();
// inserting frame delay will give correct result
//StartCoroutine(FrameDelay());
//IEnumerator FrameDelay()
//{
// yield return null;
// image.SetNativeSize();
//}
}
}