Resizable Window with Fixed Aspect Ratio?
Hey there! I've had this problem with every game I created up to this point,here's my problem:
I make 2D games. Things that are far away, like background, enemies, etc., don't load when the camera isn't close. I also really like Resizable Windows. But this means people can take the Resizable Window, drag it down, and instantly see the entire level, whether it's loaded or not. So how do I make it so that the window will always stay the same RESOLUTION, but not the same SIZE?
Again, this is a problem I've had with EVERY SINGLE GAME I ever created in Unity, and now I'm finally sick of it.
I saw someone post this:
V V V
private var lastWidth : int = 0; private var lastHeight : int = 0;
function Start () {
}
function Update () { var width = Screen.width; var height = Screen.height;
if(lastWidth != width) // if the user is changing the width
{
// update the height
var heightAccordingToWidth = width / 16.0 * 9.0;
Screen.SetResolution(width, Mathf.Round(heightAccordingToWidth), false, 0);
}
else if(lastHeight != height) // if the user is changing the height
{
// update the width
var widthAccordingToHeight = height / 9.0 * 16.0;
Screen.SetResolution(Mathf.Round(widthAccordingToHeight), height, false, 0);
}
lastWidth = width;
lastHeight = height;
}
But that's JavaScript. It doesn't work with C#. Any ideas?
Answer by Vivien_Lynn · Mar 13, 2021 at 02:22 PM
I am not sure if it is possible to resize the window while keeping a constant resolution. As far as I understand does the window size determent the resolution.
Maybe you can have some use for the script you can find here: https://forum.unity.com/threads/aspect-ratio-controller-enforce-window-aspect-ratio.599815/ With this script you can limit the min and max size of your game-window, to keep it in a range that does not break the game-experience.
Here is your java scrip in c#:
using UnityEngine;
public class AdjustWindow : MonoBehaviour
{
private int lastWidth = 0;
private int lastHeight = 0;
void Update()
{
var width = Screen.width; var height = Screen.height;
if (lastWidth != width) // if the user is changing the width
{
// update the height
var heightAccordingToWidth = width / 16.0 * 9.0;
Screen.SetResolution(width, (int)Mathf.Round((float)heightAccordingToWidth), false, 0);
}
else if (lastHeight != height) // if the user is changing the height
{
// update the width
var widthAccordingToHeight = height / 9.0 * 16.0;
Screen.SetResolution((int)Mathf.Round((float)widthAccordingToHeight), height, false, 0);
}
lastWidth = width;
lastHeight = height;
}
}
Answer by wmjoers · Jan 19 at 12:15 AM
Check out this sample projekt https://github.com/wmjoers/CameraScaler! The CameraScaler script lets you keep the aspect ratio or you can let it grow in any direction depending on your needs. Also note that you need to use a second camera to make sure you get a black letter box (it's in the sample scene).