Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question How can I scale a sprite to fit screen width

Discussion in 'Scripting' started by tomlugin100, Apr 3, 2024.

  1. tomlugin100

    tomlugin100

    Joined:
    May 6, 2023
    Posts:
    84
    Hello everyone! Thank you for reading my question!
    I have a sprite that I want to scale so that its width is the same as the screen width. Nothing I have tried has worked like this.
    I've tried changing the Draw Mode to Sliced and altering the width to 1080 (the width of my canvas) but the sprite sometimes is too wide or too narrow (depending on the device)
    How can I solve this?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,005
    If you're talking UI, you need to set the anchors properly. See below.

    If you're talking raw sprite, then the camera height (ortho) can give you the proper width by the ratio of Screen.width vs Screen.height, just do it in a little script if it must change, or make it worst-case for 1920x1080 or whatever you want.

    Here are the official docs on how to make your UI handle various resolutions and aspect ratios cleanly:

    https://docs.unity3d.com/2023.1/Documentation/Manual/HOWTO-UIMultiResolution.html

    Here are some notes on UI Anchoring, Scaling, CanvasScaler, etc:

    https://forum.unity.com/threads/inc...size-between-two-people.1130146/#post-7261747

    https://forum.unity.com/threads/game-ui-button-size-problem.1142650/#post-7337383
     
  3. tomlugin100

    tomlugin100

    Joined:
    May 6, 2023
    Posts:
    84
    Thank you @Kurt-Dekker for your response. I figured out the solution to my problem. I wasn't setting the right orthographic size for my camera. Now I set the correct sprite size under Draw Mode: Sliced and it works like a charm
     
    Kurt-Dekker likes this.