将TargetAspect设置成static以使用Unity式单例模式方便后续玩家设置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| using UnityEngine;
namespace Script.Client { public class ScreenAspect : MonoBehaviour { public static float TargetAspect = 16f / 9f; private Camera _mainCamera;
private void Awake() { _mainCamera = Camera.main;
var windowAspect = Screen.width / (float)Screen.height;
var scaleHeight = windowAspect / TargetAspect;
if (scaleHeight < 1f) { var rect = _mainCamera.rect;
rect.width = 1f; rect.height = scaleHeight; rect.x = 0; rect.y = (1f - scaleHeight) / 2f;
_mainCamera.rect = rect; } else { var scaleWidth = 1f / scaleHeight;
var rect = _mainCamera.rect;
rect.width = scaleWidth; rect.height = 1f; rect.x = (1f - scaleWidth) / 2f; rect.y = 0;
_mainCamera.rect = rect; } } } }
|