起因

项目需要做不同机型的分辨率的适配,UI 的适应还好说,GameView 修改分辨率之后,UI 就自适应了,但是场景中 Camera 的 Size 适配还需要自己动手做些工作

之前代码是直接获取Screen.width 和 Screen.height,但是当在Editor 下, 修改了GameView 的分辨率时,获取到的值是不对的

代码部分

Unity 源码参考

这里需要写两种情况, 一种是在 Editor 下, 一种是在真机下

Editor 比较麻烦, 需要反射调用 Editor 的代码,获取到正确的分辨率,当修改 GameView 分辨率时,需要手动开关这个相机,才可以触发

如果有更好的办法欢迎分享~

using Cinemachine;
using UnityEngine;

namespace ETModel {
    [ExecuteInEditMode]
    public class CameraSizeFilter : MonoBehaviour {
        public CinemachineVirtualCamera VCamera;

        [SerializeField]
        private float _defaultSize = 3.75f;

        [SerializeField]
        private float _defaultHeight = 750f;

        [SerializeField]
        private float _defualtWidth = 1624f;

        private void OnEnable() {
            float ratioHeight;
#if UNITY_EDITOR
            ratioHeight = _defualtWidth / GetGameViewRatio();
#else
            ratioHeight = _defualtWidth / Screen.width * Screen.height;
#endif
            VCamera.m_Lens.OrthographicSize = ratioHeight / _defaultHeight * _defaultSize;
        }

#if UNITY_EDITOR
        private float GetGameViewRatio() {
            var                        mouseOverWindow = UnityEditor.EditorWindow.mouseOverWindow;
            System.Reflection.Assembly assembly        = typeof(UnityEditor.EditorWindow).Assembly;
            System.Type                type            = assembly.GetType("UnityEditor.PlayModeView");

            Vector2 size = (Vector2) type.GetMethod(
                                              "GetMainPlayModeViewTargetSize",
                                              System.Reflection.BindingFlags.NonPublic |
                                              System.Reflection.BindingFlags.Static
                                          ).
                                          Invoke(mouseOverWindow, null);

            return size.x / size.y;
        }

#endif
    }
}

What doesn’t kill you makes you stronger.