目录
效果
步骤
源码
效果
步骤
1. 在“xxx.Build.cs”中添加需要使用的模块 ,这里主要使用“DesktopPlatform”模块
2. 添加后闭UE编辑器,右键点击 .uproject 文件,选择 "Generate Visual Studio project files",重新从Visual Studio编译项目
3. 打开UE编辑器,新建一个父类为蓝图函数库的C++类,这里命名为“BPL_Functions”
4. 在头文件中添加一个蓝图可调用的函数,这里命名为“GetFbxPathByDialog”,表示通过文件对话框获取选择的.fbx文件的路径,该函数需要传入两个参数,一个是文件对话框的标题,还有一个是默认的路径
5. 在源文件中先导入“DesktopPlatformModule.h”和“IDesktopPlatform.h”,然后实现函数“GetFbxPathByDialog”
6. 创建一个控件蓝图,添加一个按钮和一个“EditableText”,按钮用于打开文件对话框,EditableText用于显示被选择文件的路径
在事件图表中设置当按钮点击后调用函数“GetFbxPathByDialog”,然后将获取的地址设置给EditableText
最终运行效果如文章开头所示。
源码
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "BPL_Functions.generated.h"
UCLASS()
class GLOBEPAWNTEST_API UBPL_Functions : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
//通过文件对话框选择.fbx文件,返回选择文件的路径
UFUNCTION(BlueprintCallable, Category = "File Utility", meta = (DisplayName = "Open FBX File Dialog"))
static FString GetFbxPathByDialog(const FString& DialogTitle = TEXT("Select an FBX File"), const FString& DefaultPath = TEXT(""));
};
#include "BPL_Functions.h"
#include "DesktopPlatformModule.h"
#include "IDesktopPlatform.h"
FString UBPL_Functions::GetFbxPathByDialog(const FString& DialogTitle, const FString& DefaultPath)
{
FString OutSelectedFilePath = TEXT("");
IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get();
if (DesktopPlatform)
{
TArray<FString> OutFiles;
const FString FileTypes = TEXT("FBX Files (*.fbx)|*.fbx"); // 筛选.fbx文件
const void* ParentWindowHandle = nullptr;
FString StartPath = DefaultPath; // 文件对话框打开的默认地址
if (StartPath.IsEmpty() || !FPaths::DirectoryExists(StartPath))
{
StartPath = FPaths::ProjectDir(); // 默认为项目根目录
}
uint32 SelectionFlag = 0; // 只能选择单个文件
bool bFileSelected = DesktopPlatform->OpenFileDialog(
ParentWindowHandle,
DialogTitle,
StartPath, // 文件对话框打开的默认地址
TEXT(""), // 默认的选中文件
FileTypes, // 可选择文件的类型
SelectionFlag, // 选择文件的数量
OutFiles // 被选则文件的地址
);
if (bFileSelected && OutFiles.Num() > 0)
{
OutSelectedFilePath = OutFiles[0]; // 第1个被选择的文件
FPaths::NormalizeFilename(OutSelectedFilePath); // 标准化文件地址
return OutSelectedFilePath;
}
}
else
{
UE_LOG(LogTemp, Error, TEXT("DesktopPlatform module is not available."));
}
return OutSelectedFilePath;
}