获取Unity GameView 分辨率大小

起因

项目需要做不同机型的分辨率的适配,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
    }
}
作者:L
本文采用 CC BY-NC-SA 4.0 协议
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇