Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Bug SetNativeSize in OnEnable results in incorrect sizeDelta for non 100 Pixel Per Unit sprite

Discussion in 'UGUI & TextMesh Pro' started by unknowndevice, Jul 29, 2020.

  1. unknowndevice


    Sep 13, 2016
    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.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    4. public class ImageChanger : MonoBehaviour
    5. {
    6.     [SerializeField] Image image = default;
    7.     [SerializeField] Sprite sprite = default;
    9.     void OnEnable()
    10.     {
    11.         image.sprite = sprite;
    13.         // incorrect result if ppu is not 100
    14.         image.SetNativeSize();
    16.         // inserting frame delay will give correct result
    17.         //StartCoroutine(FrameDelay());
    18.         //IEnumerator FrameDelay()
    19.         //{
    20.         //    yield return null;
    21.         //    image.SetNativeSize();
    22.         //}
    23.     }
    24. }
  2. unknowndevice


    Sep 13, 2016
    Looking closer it seems like image.pixelsPerUnit is incorrect in the first frame OnEnable.