unity相机锁rect比例
脚本 挂在场景摄像机使用
using UnityEngine;
[ExecuteInEditMode]
public class AspectRatio : MonoBehaviour
{
//
[SerializeField] float widthUnits = 2.0f;
[SerializeField] float heightUnits = 3.0f;
void Start()
{
UpdateCameraRect();
}
#if UNITY_EDITOR
void Update()
{
UpdateCameraRect();
}
#endif
void UpdateCameraRect()
{
float targetAspect = widthUnits / heightUnits;
float windowAspect = (float)Screen.width / (float)Screen.height;
float scaleHeight = windowAspect / targetAspect;
Camera camera = GetComponent<Camera>();
Rect rect = camera.rect;
if (scaleHeight < 1.0f)
{
rect.width = 1.0f;
rect.height = scaleHeight;
rect.x = 0;
rect.y = (1.0f - scaleHeight) / 2.0f;
}
else
{
float scaleWidth = 1.0f / scaleHeight;
rect.width = scaleWidth;
rect.height = 1.0f;
rect.x = (1.0f - scaleWidth) / 2.0f;
rect.y = 0;
}
camera.rect = rect;
}
}