Search Unity

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

    unknowndevice

    Joined:
    Sep 13, 2016
    Posts:
    86
    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;
    3.  
    4. public class ImageChanger : MonoBehaviour
    5. {
    6.     [SerializeField] Image image = default;
    7.     [SerializeField] Sprite sprite = default;
    8.  
    9.     void OnEnable()
    10.     {
    11.         image.sprite = sprite;
    12.  
    13.         // incorrect result if ppu is not 100
    14.         image.SetNativeSize();
    15.  
    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

    unknowndevice

    Joined:
    Sep 13, 2016
    Posts:
    86
    Looking closer it seems like image.pixelsPerUnit is incorrect in the first frame OnEnable.
     
  3. PianistaCompany

    PianistaCompany

    Joined:
    Jan 30, 2023
    Posts:
    3
    Has Unity solved this problem? I have the same problem