在游戏开发中,全屏显示(Fullscreen)是常见的需求,特别是在游戏引擎(如 Unity、Unreal Engine、Godot 等)中。下面是几种常见平台和引擎中实现游戏全屏的通用方法:
✅ 一、Unity(C#)
方法 1:使用 SetFullResolution(Unity 2019+)
using UnityEngine;
public class FullscreenManager : MonoBehaviour
{
public void ToggleFullscreen()
{
if (Application.isEditor)
{
// 在编辑器中,直接全屏
Application.SetFullResolution(800, 600);
}
else
{
// 在运行时,全屏
Screen.fullScreen = true;
}
}
}
方法 2:使用 Screen.fullScreen(推荐)
Screen.fullScreen = Screen.fullScreen ? Screen.fullScreen : Screen.fullScreen;
说明:
Screen.fullScreen是一个枚举,可以是:
Screen.fullScreen→ 全屏Screen.borderless→ 边框模式(不全屏)Screen.display→ 显示模式(如窗口模式)
✅ 二、Unreal Engine(C++)
方法 1:使用 FMinimalRHI 的 SetFullScreen
FMinimalRHI* RHI = FMinimalRHI::Get();
if (RHI)
{
RHI->SetFullScreen(true);
}
方法 2:使用 SetViewportSize 和 SetViewportMode
FViewportMode ViewportMode = EViewportMode::FullScreen;
FViewportSize ViewportSize = FViewportSize(800, 600);
FMinimalRHI::Get()->SetViewportSize(ViewportSize, ViewportMode);
✅ 三、Godot(GDScript)
方法 1:使用 show() 和 set_fullscreen()
func _ready():
$Button.clicked.connect(_onButtonClicked)
func _onButtonClicked():
$Window.set_fullscreen(true)
方法 2:使用 Screen.set_fullscreen()
Screen.set_fullscreen(true)
✅ 四、其他平台(如 Windows 10/11)
方法:使用系统 API(如 SetWindowLong)
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int dwOldWnd, IntPtr newWnd);
public void ToggleFullscreen()
{
IntPtr hWnd = new IntPtr(-1); // 用于获取当前窗口句柄
if (GetWindowHandle(hWnd))
{
SetWindowLong(hWnd, 0x00000080, IntPtr.Zero); // 0x00000080 = WS_VISIBLE
SetWindowLong(hWnd, 0x00000040, IntPtr.Zero); // 0x00000040 = WS_VISIBLE
SetWindowLong(hWnd, 0x00000000, IntPtr.Zero); // 0x00000000 = WS_VISIBLE
SetWindowLong(hWnd, 0x00000080, IntPtr.Zero); // 0x00000080 = WS_VISIBLE
}
}
✅ 五、注意事项
| 项目 | 说明 |
|---|---|
| 全屏 vs 窗口 | 全屏模式下,窗口不会被遮挡,但可能无法最大化 |
| 分辨率 | 全屏模式下,分辨率由系统决定,可能需要调整 |
| 性能 | 全屏模式下,性能通常更好,但可能占用更多内存 |
| 兼容性 | 不同平台、不同引擎的全屏方法可能不同 |
✅ 六、总结
| 平台 | 方法 |
|---|---|
| Unity | Screen.fullScreen = true |
| Unreal Engine | FMinimalRHI::Get()->SetFullScreen(true) |
| Godot | Screen.set_fullscreen(true) |
| C++ (Unreal) | FMinimalRHI::Get()->SetFullScreen(true) |
| C# (Unity) | Screen.fullScreen = true |
| 其他 | 使用系统 API 或引擎自带的全屏方法 |
如果你是在某个特定引擎或平台下开发,可以告诉我,我可以提供更具体的代码示例。