Вы можете сохранить начальные размеры окна и сравнить их как
public float targetAspetctRatio;
private int lastWidth;
private int lastHeight;
private void Start()
{
lastWidth = Screen.width;
lastHeight = Screen.height;
// You could get the targetAspetctRatio also from the device like
targetAspetctRatio = (float)Screen.currentResolution.with / Screen.currentResolution.height;
}
private void LateUpdate()
{
if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
{
ScreenSizeChanged();
}
}
или с таймером для проверки не каждого кадра
private float timer=0;
public float Interval = 0.5f;
private void LateUpdate()
{
timer-= Time.deltaTime;
if(timer > 0) return;
timer = Interval;
if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
{
ScreenSizeChanged();
}
}
или с сопрограммой
public float Interval = 0.5f;
private void Start()
{
lastWidth = Screen.width;
lastHeight = Screen.height;
// You could get the targetAspetctRatio also from the device like
targetAspetctRatio = (float)Screen.currentResolution.with / Screen.currentResolution.height;
StartCoroutine(CheckSize);
}
private IEnumertor CheckSize()
{
while(true)
{
if(lastWidth != Screen.width || lastHeight != Screen.height || !Mathf.Approximately((float)Screen.width/Screen.height, targetAspetctRatio))
{
ScreenSizeChanged();
}
yield return new WaitForSeconds(Offset);
}
}
Чтобы установить соотношение сторон, задайте его в зависимости от высоты
Screen.SetResolution(Screen.height * targetAspetctRatio, Screen.height, false);
или от ширины
Screen.SetResolution(Screen.width, Screen.width / targetAspetctRatio, false);
Вы должны решить, каким образомидти .. в сомнения, по крайней мере, один, который вписывается в экран.Что-то вроде
private void ScreenSizeChanged ()
{
// Try to go by width first
// Check if new height would fit
if(Screen.width <= screen.currentResolution.width && Screen.width / targetAspetctRatio <= Screen.currentResolution.height)
{
Screen.SetResolution(Screen.width, Screen.width / targetAspetctRatio, false);
}
// By height as fallback
// Check if new width would fit display
else if(Screen.height <= Screen.currentResolution.height && Screen.height * targetAspetctRatio <= Screen.currentResolution.width)
{
Screen.SetResolution(Screen.height * targetAspetctRatio, Screen.height, false);
}
else
{
// Do nothing or maybe reset?
Screen.SetResolution(lastWidth, lastHeight, false);
}
// Don't fortget to store the changed values
lastWidth = Screen.width;
lastHeight = Screen.height;
}
Screen.currentResolution возвращает максимальное разрешение дисплея, а не текущий размер окна.