在项目中创建一个新的C++类

并不是任意位置都可以创建。在C++项目中会有一个专用的文件夹用来存储C++的类,需要在这里创建。

image-20240224133803394

选择继承自 Blueprint Function Library

image-20240224133921121

进行一个命名。之后会在本地工程文件中生成两个文件 .h.cpp。路径为 Project/Source/name_of_project。也可以直接在虚幻引擎中打开 Visual Studio然后在资源管理器中找到。

image-20240224134215438

编辑一下这两个代码文件:

对于 .h文件,定义了一个名为 URWer的蓝图函数库类,提供了两个静态函数 ReadTxtWriteTxt,并且设置 BlueprintCallable可以方便地在蓝图中调用。

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "RWer.generated.h"

/**
 * 
 */
UCLASS()
class LIDARPROJECT_API URWer : public UBlueprintFunctionLibrary
{
    GENERATED_BODY()

    UFUNCTION(BlueprintCallable)
    static FString ReadTxt(FString Filename);

    UFUNCTION(BlueprintCallable)
    static bool WriteTxt(FString content, FString Filename);


};

对于 .cpp文件,完善了两个函数的内容。Containers/UnrealString.h: 包含了 FString类的定义,用于处理字符串。

// Fill out your copyright notice in the Description page of Project Settings.


#include "RWer.h"
#include "Containers/UnrealString.h"

FString URWer::ReadTxt(FString Filename) {

    FString resultString;

    FFileHelper::LoadFileToString(resultString, *(FPaths::ProjectContentDir() + Filename));

    return resultString;

}

bool URWer::WriteTxt(FString content, FString filename) {
    bool result;
    content.Append("\n");
    result = FFileHelper::SaveStringToFile(content, *(FPaths::ProjectContentDir() + filename), FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), FILEWRITE_Append);
    return result;

}

重新加载虚幻引擎后,即可在蓝图中调用这两个函数。

image-20240224134723063

:两个函数中的 filename参数的起始路径是 Content文件夹。建议在 Content文件夹下新建子文件夹 Txt并在其中存储 .txt文件进行读写。此时 filename变量应该为 Txt/1.txt,蓝图中可以用 /斜杠表示路径。

image-20240224134909947

最后修改:2024 年 02 月 24 日
如果觉得我的文章对你有用,请随意赞赏