在Unreal Engine 5 (UE5) 中,如果想判断当前场景是否处于虚拟现实(VR)模式,可以使用几种不同的方法来实现这一功能。
以下是一些常见的方法:

    1. 使用 GEngine 和 GIsEditor
    1. 使用 FVRPluginFunctionLibrary
    1. 使用 IModularFeatures 和 FVRPlugin
    1. 使用蓝图(Blueprint)

第一种方法:使用 GEngine 和 GIsEditor

可以通过检查 GEngine 的 IsStereoscopicPass 函数或者使用 GIsEditor 来判断是否处于 VR 模式。这种方法通常在运行时使用。

1.创建一个基于蓝图函数库的C++类(MyBlueprintFunctionLibrary)

过程参照 UE5 蓝图调用C++函数方式 文章

2.在MyBlueprintFunctionLibrary类中添加如下代码

在MyBlueprintFunctionLibrary.h添加:

1
2
UFUNCTION(BlueprintCallable)
static bool IsInVRMode();

在MyBlueprintFunctionLibrary.cpp添加:

1
2
3
4
5
6
7
#include "IXRTrackingSystem.h" // 引入 XR 跟踪系统接口定义
#include "Engine/Engine.h" // 确保已包含 Engine 头文件(已在错误信息中提及)

bool UMyBlueprintFunctionLibrary::IsInVRMode()
{
return GEngine && GEngine->XRSystem.IsValid() && GEngine->XRSystem->IsHeadTrackingAllowed();
}

3.在游戏初始时的蓝图中引用函数

返回true为是在VR模型运行

第二种方法:使用 FVRPluginFunctionLibrary

UE5 提供了 FVRPluginFunctionLibrary 类,可以使用它来查询 VR 状态。首先确保项目启用了 VR 支持,并且在项目设置中正确配置了 VR 插件。

1
2
3
4
5
6
7
#include "HeadMountedDisplayFunctionLibrary.h"

bool IsInVRMode()
{
// 检查是否处于 VR 模式
return UHeadMountedDisplayFunctionLibrary::IsHeadMountedDisplayEnabled();
}

第三种方法:使用 IModularFeatures 和 FVRPlugin

UE5 中,通过查询模组功能来获取 VR 插件的状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include "Modules/ModuleManager.h"
#include "IXRTrackingSystem.h"
#include "IXRSystem.h"

bool IsInVRMode()
{
// 获取 XRSystem 模块
if (IXRSystem* XRSystem = FModuleManager::Get().LoadModuleChecked<IXRSystem>("XRSystem"))
{
return XRSystem->IsHeadTrackingAllowed();
}
return false;
}

第四种方法:使用蓝图(Blueprint)

在蓝图编辑器中使用“Is Head Mounted Display Enabled”节点。

  • 1.在事件图中添加一个“条件”节点。
  • 2.从“Head Mounted Display”类别中拖拽“Is Head Mounted Display Enabled”节点到条件节点。
  • 3.根据这个节点的输出连接其他逻辑。

以上方法建议第一种。