1.正交模式(2D)
Camera组件的Projection为Orthographic即正交模式.
添加脚本,放入场景物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenInit : MonoBehaviour
{
private void Awake()
{
//1920/1080 是编辑模式下固定的屏幕宽度和屏幕高度,Screen.Height和Screen.Width是实际屏幕高度和实际屏幕宽度
Camera.main.orthographicSize = Camera.main.orthographicSize * 1920 / 1080 * Screen.height / Screen.width;
}
}
记得把Canvs Scaler上的UI Scale Mode 换成Screen With Screen Size
测试得知:如上公式会让摄像机可视宽度永远不会变化,而高度还是会变的,若需要高度不变、宽度变化的话,保持原样即可。也就是你不用看文章方法去做了,unity原本的方法就是高度永不变,宽度变化。
2.透视模式(3D)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenInit : MonoBehaviour
{
private void Awake()
{
//Camera.main.fieldOfView是用来设置摄像机视野的大小
float targetHight = 1920.0f;
if (1080*Screen.height>1920*Screen.width)
{
targetHight = 1080f * Screen.height / Screen.width;
}
Camera.main.fieldOfView *= (targetHight/1920.0f);
}
}