UE4里的全局变量,全局函数,便于工程里其他模块代码访问,以及Blueprint的访问

本文详细介绍了如何在Unreal Engine中使用全局数据存储类(classSingle)来存储不常改变的全局数据,并通过Blueprint实现跨cpp和Blueprint的访问。此外,还展示了如何创建BlueprintFunctionLibrary来提供全局功能函数,使其可以在任意Blueprint中调用。通过实例演示了如何设置工程单例,确保数据的一致性和高效访问。

1. 单例

Unreal Engine的wiki上,Rama给了一个教程,教大家如何存储不常改变的全局数据,便于运行时从任何cpp或者Blueprint访问之。

https://wiki.unrealengine.com/Global_Data_Access,_Data_Storage_Class_Accessible_From_Any_CPP_or_BP_Class_During_Runtime!

要点如下:

1. 创建一个继承自UObject的class Single,需要标注UClass(Blueprintable, BlueprintType)。

    在创建的class Single里放置一些全局变量后,需要添加UFunction,实现全局访问数据的接口函数。

2. 最重要的是,运行工程后,在Editor里需要设置工程的单例。

     运行打开编辑器后,创建基于步骤1里的class Single的Blueprint, BP_MySingle;

     然后修改编辑器的配置参数:Project Settings->Engine->General, 将Game Singleton Class设置为你自己的单例BP: BP_MySingle!  注意,用的是基于class Single的Blueprint, 不是class Single本身!

单例更偏向于数据的存取和访问,而且是一些很少改变的数据。 如何处理那些全局的功能函数呢?


2. BlueprintFunctionLibrary

创建可以在任意BP里访问的功能函数。

创建一个继承自UBlueprintFunctionLibrary的class,  在其中声明你需要的功能函数。

UFUNCTION(BlueprintPure) or UFUNCTION(BlueprintCallable)声明。同时函数请设置为static属性。
若函数带有BlueprintPure属性,则说明此函数不会修改任何游戏状态,因此无需exec链的触发(在Blueprint中体现为没有白线输入),可以在任何时刻被调用获取其结果。

.h

#pragma once
#include "SolusDataSingleton.h"
#include "SolusDataSingletonLibrary.generated.h"

UCLASS()
class USolusDataSingletonLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_UCLASS_BODY()

	UFUNCTION(BlueprintPure, Category = "Solus Data Singleton")
	static USolusDataSingleton* GetSolusData(bool& IsValid);


	UFUNCTION(BlueprintCallable, Category = "VictoryBPLibrary")
	static FString GetHappyMessage();

	UFUNCTION(BlueprintCallable, Category = "VictoryBPLibrary")
	static bool SaveStringTextToFile(FString SaveDirectory, FString FileName, FString SaveText, bool AllowOverWriting=false);

	UFUNCTION(BlueprintCallable, Category = "ScreenResolution")
	static void GetDisplayAdapterScreenResolutions();
};

.cpp

#include "MyThirdPersonCode.h"
#include "SolusDataSingletonLibrary.h"

USolusDataSingletonLibrary::USolusDataSingletonLibrary(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
{

}

USolusDataSingleton* USolusDataSingletonLibrary::GetSolusData(bool& IsValid)
{
	IsValid = false;
	USolusDataSingleton* DataInstance = Cast<USolusDataSingleton>(GEngine->GameSingleton);
	if (!DataInstance)
	{
		return NULL;
	}
	if (!DataInstance->IsValidLowLevel())
	{
		return NULL;
	}
	IsValid = true;
	return DataInstance;
}

FString USolusDataSingletonLibrary::GetHappyMessage()
{
	return FString("Victory! Give me a big Smile. Victory BP Works!");
}

bool USolusDataSingletonLibrary::SaveStringTextToFile(FString SaveDirectory, FString FileName, FString SaveText, bool AllowOverWriting/* =false */)
{
	IPlatformFile& F = FPlatformFileManager::Get().GetPlatformFile();
	if (!F.DirectoryExists(*SaveDirectory))
	{
		F.CreateDirectoryTree(*SaveDirectory);
		if (!F.DirectoryExists(*SaveDirectory))
		{
			return false;
		}
	}

	SaveDirectory += "\\";
	SaveDirectory += FileName;

	if (!AllowOverWriting)
	{
		if (!F.FileExists(*SaveDirectory))
		{
			return false;
		}
	}

	return FFileHelper::SaveStringToFile(SaveText, *SaveDirectory);
}

DEFINE_LOG_CATEGORY_STATIC(MyLog, All, All)
void USolusDataSingletonLibrary::GetDisplayAdapterScreenResolutions()
{
	FScreenResolutionArray Resolutions;
	if (RHIGetAvailableResolutions(Resolutions, false))
	{
		for (const FScreenResolutionRHI& EachResolution : Resolutions)
		{
			FString disInfo = FString("X=") + FString::FromInt(EachResolution.Width) + FString(" Y=") + FString::FromInt(EachResolution.Height);
			GEngine->AddOnScreenDebugMessage(-1, 5.0, FColor::Blue, disInfo);
			UE_LOG(MyLog, Warning, TEXT("DefaultAdapter - %4d x %4d @ %d"), EachResolution.Width, EachResolution.Height, EachResolution.RefreshRate);
		}
	}
	else
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.0, FColor::Blue, "Screen Resolutions could not be obtained");
		UE_LOG(MyLog, Error, TEXT("Screen Resolutions could not be obtained"));
	}
}






<think>我们正在讨论Unreal Engine中的文件对话框功能。用户询问是否存在OpenFileDialog函数。 在Unreal Engine中,确实有用于打开文件对话框的功能,但需要注意的是,这并不是一个单一的蓝图函数,而是一组节点,并且通常需要平台支持(例如Windows、Mac等桌面平台)。 关键点: 1. Unreal Engine提供了`Platform File`和`Desktop Platform`模块来处理文件操作和对话框。 2. 打开文件对话框的主要节点是`Desktop Platform`模块中的`Open File Dialog`节点(在蓝图中通过蓝图函数库调用)。 3. 该节点仅在支持桌面平台的应用程序中有效(如Windows、Mac、Linux),在移动平台或游戏主机上不可用。 步骤: - 首先,我们需要获取`Desktop Platform`的子系统。 - 然后调用`Open File Dialog`函数,并传入必要的参数。 参数说明: - Parent Window Handle: 父窗口句柄(通常可以传0,表示默认主窗口) - Dialog Title: 对话框标题 - Default Path: 默认打开的路径 - Default File: 默认选中的文件 - File Types: 文件类型过滤器,格式为"文件类型描述|*.扩展名",多个类型用分号隔开,例如:"Image Files|*.jpg;*.png" - Flags: 对话框标志(多选等) - Out File Names: 返回选择的文件路径(数组,因为可能多选) 注意:在蓝图中,这个节点是异步的,会立即返回,但结果需要通过委托(事件)来获取。 蓝图示例: ```mermaid graph LR A[调用 Open File Dialog] --> B[绑定事件到 On File Dialog Closed] B --> C[处理返回的文件路径] ``` 具体节点: - 在蓝图函数库中:`Desktop Platform` -> `Open File Dialog` - 事件:`On File Dialog Closed`(当对话框关闭时触发,并返回选择的文件列表) 由于这是一个异步操作,我们需要在蓝图中使用事件来等待结果。 示例代码(蓝图伪代码): ```blueprint // 打开文件对话框 [Open File Dialog] -> Parent Window Handle: 0 Dialog Title: '选择文件' Default Path: 'C:/' Default File: '' File Types: '所有文件|*.*|图片文件|*.jpg;*.png' Flags: 0 // 0表示单选,可以设置多选等 (Out File Names: FileNames) // 返回的文件路径数组 (On File Dialog Closed: Event) // 事件绑定 // 事件处理 Event On File Dialog Closed -> [For Each File in FileNames] -> [Print String: File] // 打印每个选中的文件路径 ``` 另外,Unreal Engine还提供了类似的`Save File Dialog`节点用于保存文件。 限制: - 这些对话框只能在桌面平台使用,在控制台或移动设备上调用会失败。 - 在编辑器环境下(Play in Editor)可以正常使用,但在打包后的游戏中需要确保平台支持。 如果用户需要在非桌面平台使用文件选择功能,可能需要使用平台特定的API或编写自定义模块。 相关问题: 1. 如何在Unreal Engine中实现多文件选择? 2. 如何限制文件对话框只能选择特定类型的文件? 3. 在Unreal Engine中如何实现文件夹选择对话框? 4. 文件对话框在打包后的游戏中是否可用? 注意:在C++中,我们可以直接使用`IDesktopPlatform`模块,但在蓝图中,我们使用上述的蓝图节点。 因此,回答用户的问题:Unreal Engine中有`OpenFileDialog`的功能,但不是一个简单的函数,而是一组节点,并且需要正确使用。</think>### Unreal Engine 中的 OpenFileDialog 函数详解 在 Unreal Engine 中,**确实存在 OpenFileDialog 功能**,但它是通过 **Desktop Platform 模块** 实现的,而非单一蓝图函数。以下是核心实现方式: #### 1. 核心节点与用法 ```mermaid graph LR A[获取桌面平台子系统] --> B[调用OpenFileDialog] B --> C[处理返回的文件路径] ``` **关键蓝图节点:** ```blueprint // 打开文件对话框 [Desktop Platform] -> [Open File Dialog] -> Parent Window Handle: 0 Dialog Title: "选择文件" Default Path: "C:/Documents" Default File: "" File Types: "图像文件|*.jpg;*.png|所有文件|*.*" Flags: 0 // 0=单选,1=多选 (Out File Names: FilePaths) // 返回选择的文件路径数组 (Return Value: Success) ``` #### 2. 完整蓝图示例 ```blueprint // 1. 获取桌面平台子系统 [Get Game Instance] -> [Get Subsystem: DesktopPlatform] // 2. 打开文件对话框 [Open File Dialog] -> Parent Window Handle: 0 Dialog Title: "选择纹理文件" Default Path: "" Default File: "" File Types: "PNG图像|*.png|JPEG图像|*.jpg" Flags: 0 // 3. 处理结果 [Branch] -> (Success) True -> [For Each File] -> [Load Object from Path] -> (Texture) [Set Texture to Material] False -> [Print String: "取消选择"] ``` #### 3. 关键参数说明 | 参数 | 说明 | 示例值 | |------|------|--------| | **File Types** | 文件类型过滤器 | `"文本文件|*.txt"` | | **Flags** | 对话框选项 | `0`=单选, `1`=多选 | | **Default Path** | 初始路径 | `"C:/Project/Content"` | | **Out File Names** | 返回路径数组 | `["D:/image.png"]` | #### 4. 平台限制与注意事项 1. **仅支持桌面平台** Windows/Mac/Linux 可用,移动端(Android/iOS)不可用[^1] 2. **路径格式要求** 返回路径为绝对路径,需转换为引擎相对路径: ```blueprint [Convert to Relative Path] -> Base Path: "/Game/" Full Path: FilePath ``` 3. **异步操作建议** 大型文件操作应使用异步加载: ```blueprint [Async Load Asset] -> Asset Path: FilePath [On Loaded] -> (Loaded Texture) ``` > **最佳实践:** > - 打包后使用需添加 `-AllowDesktopPlatformDialogs` 启动参数 > - 敏感操作需配合 `File I/O 权限` 设置[^2] > - 建议封装成可重用的 **蓝图函数库**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值