Search Unity

Feedback Maintaining Aspect Ration of Runtime Sprites

Discussion in 'UGUI & TextMesh Pro' started by khanstruct, May 26, 2023.

  1. khanstruct

    khanstruct

    Joined:
    Feb 11, 2011
    Posts:
    2,869
    I was struggling with a piece of my UI yesterday, and wasn't able to find much help online. I did finally find a solution, but I thought I'd share it here (and possibly have it addressed by the Unity folk).

    As part of my game's inventory system, I have sprites appear in the player's hotbar when they pick something up. This is a 2d game, so I'm just using the item's own sprite for this. The problem is that the images were showing up stretched to fill the image.

    Obviously, you can just check the "Preserve Aspect" in the Image Component, BUT! This checkbox doesn't appear unless you actually have a source image assigned to the component. As these are assigned at runtime. I don't get that checkbox in the inspector.

    What I did was assign an image, check the "Preserve Aspect" box, then delete the image. The component apparently remembers that it was checked, and will carry that over at runtime.

    This works, but it seems a little flimsy for my tastes, so I'll likely try "Image.preserveAspect = true" somewhere in the code just to make sure.