Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question I want to resize the window size while maintaining the aspect ratio in Unity Wndows.

Discussion in 'Windows' started by Sushi8819, Nov 11, 2023.

  1. Sushi8819

    Sushi8819

    Joined:
    Oct 20, 2023
    Posts:
    17
    As the title says, I want to resize the window while maintaining the aspect ratio in a resizable window.
    I created a GameObject with the following code attached, but when I drag the window, the size changes are not smooth, and it stutters.
    My settings are as follows. Any advice would be greatly appreciated.
    Thank you.

    Code (CSharp):
    1.  
    2.         int width = Screen.width;
    3.         int height = Screen.height;
    4.  
    5.         if (lastWidth != width)
    6.         {
    7.             float heightAccordingToWidth = (float)width / 16.0 * 9.0;
    8.             Screen.SetResolution(width, (int)Mathf.Round(heightAccordingToWidth), false, 0);
    9.         }
    10.         else if (lastHeight != height)
    11.         {
    12.             float widthAccordingToHeight = (float)height / 9.0 * 16.0;
    13.             Screen.SetResolution((int)Mathf.Round(widthAccordingToHeight), height, false, 0);
    14.         }
    15.  
    16.         lastWidth = width;
    17.         lastHeight = height;
    upload_2023-11-11_13-42-56.png


    upload_2023-11-11_13-43-14.png
     
  2. Tautvydas-Zilys

    Tautvydas-Zilys

    Unity Technologies

    Joined:
    Jul 25, 2013
    Posts:
    10,745
    Unfortunately we do not have window size enforcement feature in Unity. As you discovered, calling SetResolution every time the window size is different than what you expect results in a terrible end user experience so I would highly recommend not doing it.