Search Unity

Best way to get game window size

Discussion in 'Scripting' started by alesimula, Feb 11, 2020.

  1. alesimula

    alesimula

    Joined:
    Mar 27, 2019
    Posts:
    7
    I want to get the updated size of the current game window to do some calculations for PixelPerfectCamera, but for some reason
    Screen.width
    and
    Screen.height
    are not updated (always show the windows size from when the game was started).

    I found the member
    Display.main.renderingHeight
    which seems to work, but I don't know how efficient it is (I'm calling it every update to check if the game window size has changed) or if it's a good idea to use it

    Here is a snippet to show what I'm trying to do

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5.  
    6. public class Camera : MonoBehaviour {
    7.     UnityEngine.Experimental.Rendering.Universal.PixelPerfectCamera pixelComponent;
    8.     UnityEngine.Camera camera;
    9.     private Resolution resolution;
    10.  
    11.     private bool isWindowResized {get {
    12.         Resolution newResolution = new Resolution();
    13.         var display = Display.main;
    14.         newResolution.height = display.renderingHeight;
    15.         newResolution.width = display.renderingWidth;
    16.         bool changed = resolution.width != newResolution.width || resolution.height != newResolution.height;
    17.         resolution = newResolution;
    18.         return changed;
    19.     }}
    20.  
    21.     private void updateResolution() {
    22.         void updateRes(int width, bool crop) {
    23.             pixelComponent.refResolutionX = width;
    24.             pixelComponent.cropFrameX = crop;
    25.         }
    26.      
    27.         if (isWindowResized) {
    28.             pixelComponent.refResolutionY = 180;
    29.             var bestFittingHeight = 180*(int)(resolution.height/180);
    30.             float aspectRatio = ((float)resolution.width)/bestFittingHeight;
    31.             //TODO add a 'maximum aspect ratio' game option
    32.             if (aspectRatio >= 16f/9) updateRes(320, true); //16:9
    33.             else if (aspectRatio >= 16f/10) updateRes(288, false); //16:10
    34.             else if (aspectRatio >= 3f/2) updateRes(270, false); //3:2
    35.             else updateRes(240, false); //4:3
    36.         }
    37.     }
    38.  
    39.     // Start is called before the first frame update
    40.     void Start() {
    41.         camera = gameObject.GetComponent<UnityEngine.Camera>();
    42.         pixelComponent = gameObject.GetComponent<UnityEngine.Experimental.Rendering.Universal.PixelPerfectCamera>();
    43.     }
    44.  
    45.     // Update is called once per frame
    46.     void Update() {
    47.         updateResolution();
    48.     }
    49. }
    50.