使用这个脚本的最后其实都要下面这个方法
public static Vector2 GetScreenResolution() { Vector2 gameViewSize; //使用宏编译主要是为了打包的时候不会报错 #if UNITY_EDITOR gameViewSize = GameViewSize(); #else gameViewSize = new Vector2(Screen.currentResolution.width, Screen.currentResolution.height) ; #endif return gameViewSize; }根据反射
using UnityEngine; public class GetGameViewSize : MonoBehaviour { private void OnEnable() { GameViewSize(); } #if UNITY_EDITOR private Vector2 GameViewSize() { 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; } #endif }
这个代码经过测试能在编辑器运行,试过几次都能正确输出Game视图的尺寸。
屏幕尺寸是1920*1080,则最大化Game视图的时候尺寸和这个基本一致。
根据UI
最后在有canvas的情况下,想了个方法获得屏幕的分辨率
#if UNITY_EDITOR int canvasDisplay = RootCanvasTransform.GetComponent<Canvas>().targetDisplay; float editorWidth = Display.displays[canvasDisplay].renderingWidth; float editorHeight = Display.displays[canvasDisplay].renderingHeight; #else
RootCanvasTransform指定那个display才能获得对应的GameView窗口 这个做法在做多屏应用的时候 应该也能获得所需canvas对应的display的分辨率 所以一个全屏扩展图片的做法是
#if UNITY_EDITOR int canvasDisplay = RootCanvasTransform.GetComponent<Canvas>().targetDisplay; float screenWidth = Display.displays[canvasDisplay].renderingWidth; float screenHeight = Display.displays[canvasDisplay].renderingHeight; #else float screenWidth = Screen.currentResolution.width; float screenHeight = Screen.currentResolution.height; #endif ... hangerRectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, screenWidth); hangerRectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, screenHeight); ...