Unity Editor中如何获取游戏渲染区域(红色框)的Rect几何信息?
如何获取Unity Editor中游戏渲染区域的精确Rect信息
我需要获取Unity Editor中游戏实际渲染区域(对应问题中的红色框)的Rect边界信息,坐标可以是相对于显示器的绝对坐标,或相对于GameView窗口的相对坐标。
我尝试过通过反射获取GameView的位置:
private Rect GetMainGameViewPosition() { System.Reflection.Assembly assembly = typeof(EditorWindow).Assembly; Type type = assembly.GetType("UnityEditor.GameView"); EditorWindow gameview = EditorWindow.GetWindow(type); return gameview.position; }
但这段代码返回的是包含标签栏、控制栏的GameView整体窗口(对应问题中的黄色框),其x、y坐标是"Scene/Game"标签栏的左上角,宽高包含了窗口的非渲染区域,无法满足需求。
我的核心需求是:获取游戏实际渲染区域(红色框)的几何信息,且支持适配当前缩放比例(1x-10x)和平移操作——我需要将眼动追踪设备的显示器坐标映射到该区域,实现眼动输入与游戏内容的关联。
解决方案
通过反射访问Unity Editor内部的GameView私有成员,获取渲染区域的相对位置,再结合缩放比例和平移偏移计算出精确的屏幕坐标:
using UnityEngine; using UnityEditor; using System.Reflection; public static class GameViewRenderAreaHelper { public static Rect GetGameRenderAreaRect() { // 获取GameView类型实例 Assembly editorAssembly = typeof(EditorWindow).Assembly; Type gameViewType = editorAssembly.GetType("UnityEditor.GameView"); EditorWindow gameView = EditorWindow.GetWindow(gameViewType); // 获取渲染区域相对于GameView窗口的Rect FieldInfo gameViewRectField = gameViewType.GetField("m_GameViewRect", BindingFlags.Instance | BindingFlags.NonPublic); Rect relativeRenderRect = (Rect)gameViewRectField.GetValue(gameView); // 转换为屏幕绝对坐标 Rect screenRenderRect = new Rect( gameView.position.x + relativeRenderRect.x, gameView.position.y + relativeRenderRect.y, relativeRenderRect.width, relativeRenderRect.height ); // 获取当前缩放比例 MethodInfo getZoomMethod = gameViewType.GetMethod("GetZoomFactor", BindingFlags.Instance | BindingFlags.NonPublic); float zoomFactor = (float)getZoomMethod.Invoke(gameView, null); // 获取视口平移偏移(仅缩放>1时生效) FieldInfo offsetField = gameViewType.GetField("m_Offset", BindingFlags.Instance | BindingFlags.NonPublic); Vector2 viewportOffset = (Vector2)offsetField.GetValue(gameView); // 计算实际可见的游戏内容区域(考虑缩放和平移) Rect visibleContentRect = new Rect( screenRenderRect.x + viewportOffset.x * zoomFactor, screenRenderRect.y + viewportOffset.y * zoomFactor, screenRenderRect.width / zoomFactor, screenRenderRect.height / zoomFactor ); return visibleContentRect; } }
代码说明
- 基础渲染区域:通过
m_GameViewRect获取游戏渲染区域相对于GameView窗口的位置,转换为屏幕绝对坐标后,就是红色框的外层边界。 - 缩放适配:调用
GetZoomFactor获取当前缩放比例,用于将渲染区域的像素尺寸转换为游戏内容的实际尺寸。 - 平移适配:通过
m_Offset获取视口拖拽的偏移量,结合缩放因子计算出当前可见的游戏内容区域的屏幕坐标。
注意事项
- 反射依赖Unity Editor的内部实现,不同版本(如2020/2021/2022)可能存在字段/方法名称差异,需自行测试适配。
- 若不需要考虑视口平移(仅需渲染区域的外层框),可去掉
viewportOffset相关计算,直接返回screenRenderRect。 - 眼动坐标映射示例:将眼动的屏幕坐标减去
visibleContentRect.x和visibleContentRect.y,再除以区域宽高得到归一化坐标,即可映射到游戏相机的视口或世界坐标。
内容的提问来源于stack exchange,提问作者kennethfm
相关产品推荐
相关产品推荐

