UE4でテキストファイルを読み込む方法

UE4の開発中に頻繁に変更されるテキストファイルを読み込みたいときのメモ。
残念ながらUE4のBPにはテキストファイルを扱う機能がありませんが、以下の方法で読めるようになります。



まずでいきなりですが新規C++クラスを作成します。
(C++わからん、という人でもコピペだけでどうにかなるかも)
作成するのは、成果物がBPで扱えるBlueprint Function Libraryになります。

フォルダやクラス名を適当に決めたら、VisualStudioが開きます。
まず.hファイルに定義を書きます。
ここではScriptLoaderというクラスを作成することにします。
書いたコードはこんな感じ。
// ScriptLoader.h

UCLASS()
class MINIADV_API UScriptLoader : public UBlueprintFunctionLibrary
{
 GENERATED_BODY()
 
 UFUNCTION(BlueprintCallable, Category = "MyBPLibrary")
 static void ScriptLoad(FString& FileData, bool& Success);

};

// ScriptLoader.cpp

#include "ScriptLoader.h"
#include "FileHelpers.h"
#include "Engine.h"


void UScriptLoader::ScriptLoad(FString& FileData, bool& Success)
{
 if (GEngine)
 {
  FString FilePath = "d:\\test.txt";

  if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*FilePath))
  {
   Success = false;
   return;
  }

  const int64 FileSize = FPlatformFileManager::Get().GetPlatformFile().FileSize(*FilePath);
  FFileHelper::LoadFileToString(FileData, *FilePath);
  Success = true;

 }
 Success = false;
}
これをコンパイルすると、UE4で以下のように呼び出せるようになります。

作成したノードはこちら。

Successから読み込みの成否が返ります。
このままだとファイル名の取り回しが面倒なので、ファイル名をBP側で指定できるようにします。
// ScriptLoader.h

 UFUNCTION(BlueprintCallable, Category = "MyBPLibrary")
 static void ScriptLoad(FString Filename, FString& FileData, bool& Success);
 
// ScriptLoader.cpp
void UScriptLoader::ScriptLoad(FString Filename, FString& FileData, bool& Success)
{
 if (GEngine)
 {
  FString FilePath = FPaths::GameContentDir() + Filename;

  if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*FilePath))
  {
   Success = false;
   return;
  }

  const int64 FileSize = FPlatformFileManager::Get().GetPlatformFile().FileSize(*FilePath);
  FFileHelper::LoadFileToString(FileData, *FilePath);
  Success = true;

 }
 Success = false;
これで、こんな風にBP上でファイル名を指定できるようになりました。

ディレクトリはGameContentDirなので、contentフォルダがルートになります。

まだまだいろいろと課題がありますが、これでとりあえず読めるはずです。