대왕휴지의 개발 공부

[Unity] 해상도 고정해주는 스크립트 본문

Unity

[Unity] 해상도 고정해주는 스크립트

대왕휴지 2023. 2. 11. 17:01

 

어떤 해상도를 하던

1920*1080 해상도로 맞춰주는 코드

 

 

canvas에 넣어서 사용한다.

Canvas Scaler에 Scale With ScreenSize 바꿔주는 거 잊지말자!!(한번 까먹고 안해서 개고생함)

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//Reference https://giseung.tistory.com/19
public class Resolution : MonoBehaviour
{
    public int setWidth = 1920; // 사용자 설정 너비
    public int setHeight = 1080; // 사용자 설정 높이

    private void Start()
    {
        SetResolution(); // 초기에 게임 해상도 고정
    }

    /* 해상도 설정하는 함수 */
    public void SetResolution()
    {
        int deviceWidth = Screen.width; // 기기 너비 저장
        int deviceHeight = Screen.height; // 기기 높이 저장

        Screen.SetResolution(setWidth, (int)(((float)deviceHeight / deviceWidth) * setWidth), true); // SetResolution 함수 제대로 사용하기

        if ((float)setWidth / setHeight < (float)deviceWidth / deviceHeight) // 기기의 해상도 비가 더 큰 경우
        {
            float newWidth = ((float)setWidth / setHeight) / ((float)deviceWidth / deviceHeight); // 새로운 너비
            Camera.main.rect = new Rect((1f - newWidth) / 2f, 0f, newWidth, 1f); // 새로운 Rect 적용
        }
        else // 게임의 해상도 비가 더 큰 경우
        {
            float newHeight = ((float)deviceWidth / deviceHeight) / ((float)setWidth / setHeight); // 새로운 높이
            Camera.main.rect = new Rect(0f, (1f - newHeight) / 2f, 1f, newHeight); // 새로운 Rect 적용
        }
    }


}