|
| 1 | +using System.Collections; |
| 2 | +using System.Collections.Generic; |
| 3 | +using UnityEngine; |
| 4 | + |
| 5 | +public class AutoResolution : MonoBehaviour |
| 6 | +{ |
| 7 | + public int setWidth = 1440; |
| 8 | + public int setHeight = 2560; |
| 9 | + |
| 10 | + private void Start() |
| 11 | + { |
| 12 | + // Get the main camera and its current dimensions |
| 13 | + Camera camera = Camera.main; |
| 14 | + Rect rect = camera.rect; |
| 15 | + |
| 16 | + // Calculate the scale height and width of the screen |
| 17 | + float scaleHeight = ((float)Screen.width / Screen.height) / ((float)9 / 16); |
| 18 | + float scaleWidth = 1f / scaleHeight; |
| 19 | + |
| 20 | + // Adjust the camera's dimensions based on the scale height and width |
| 21 | + if (scaleHeight < 1) |
| 22 | + { |
| 23 | + rect.height = scaleHeight; |
| 24 | + rect.y = (1f - scaleHeight) / 2f; |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + rect.width = scaleWidth; |
| 29 | + rect.x = (1f - scaleWidth) / 2f; |
| 30 | + } |
| 31 | + |
| 32 | + camera.rect = rect; |
| 33 | + |
| 34 | + SetResolution(); |
| 35 | + } |
| 36 | + |
| 37 | + public void SetResolution() |
| 38 | + { |
| 39 | + // Get the current device's screen dimensions |
| 40 | + int deviceWidth = Screen.width; |
| 41 | + int deviceHeight = Screen.height; |
| 42 | + |
| 43 | + // Set the screen resolution to the desired dimensions, while maintaining aspect ratio |
| 44 | + Screen.SetResolution(setWidth, (int)(((float)deviceHeight / deviceWidth) * setWidth), true); |
| 45 | + |
| 46 | + // Adjust the camera's dimensions based on the new resolution |
| 47 | + if ((float)setWidth / setHeight < (float)deviceWidth / deviceHeight) |
| 48 | + { |
| 49 | + float newWidth = ((float)setWidth / setHeight) / ((float)deviceWidth / deviceHeight); |
| 50 | + Camera.main.rect = new Rect((1f - newWidth) / 2f, 0f, newWidth, 1f); |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + float newHeight = ((float)deviceWidth / deviceHeight) / ((float)setWidth / setHeight); |
| 55 | + Camera.main.rect = new Rect(0f, (1f - newHeight) / 2f, 1f, newHeight); // 새로운 Rect 적용 |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments