UE4自身提供的一种读写文件的组件:UDataTable。好处就是不用自己写fopen、fclose等 c++ stl API相关的逻辑,避开不同平台的差异;坏处就是你想要的功能DataTable没有实现,那么还得用fopen自己发挥。
读写excel需要导出为CSV文件,目前还不支持*.XLS格式。
下面官方文档中关于用C++代码定义行结构的用法没有具体说明:
如果是蓝图创建DataTable,那么行结构Struct也可以用UE4提供的Struct组件,创建方式是:add new -》 Blueprints -》 Structure,然后再这个Structure中设置行结构。
如果是用C++代码创建DataTable,直接new C++ class,选择继承DataTable。另外FTableRowBase可以直接定义在自定义DataTable的头文件中,例如:
#pragma once
#include "Engine/DataTable.h"
#include "CharactersDT.generated.h"
USTRUCT(BlueprintType)
struct FLevelUpData : public FTableRowBase
{
GENERATED_USTRUCT_BODY()
public:
FLevelUpData()
: XPtoLvl(0)
, AdditionalHP(0)
{}
/** The 'Name' column is the same as the XP Level */
/** XP to get to the given level from the previous level */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LevelUp)
int32 XPtoLvl;
/** Extra HitPoints gained at this level */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LevelUp)
int32 AdditionalHP;
/** Icon to use for Achivement */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LevelUp)
TAssetPtr<UTexture> AchievementIcon;
};
Using excel to store gameplay data - DataTables
https://wiki.unrealengine.com/Using_excel_to_store_gameplay_data_-_DataTables
Data Driven Gameplay Elements
https://docs.unrealengine.com/latest/INT/Gameplay/DataDriven/index.html
Driving Gameplay with Data from Excel
https://forums.unrealengine.com/showthread.php?12572-Driving-Gameplay-with-Data-from-Excel
用蓝图操作DataTable的方法:
Unreal Engine, Datatables for Blueprints (build & Use)
https://www.youtube.com/watch?v=a8jMl69alrg
Excel to Unreal
https://www.youtube.com/watch?v=WLv67ddnzN0
如何用C++代码动态加载*.CSV
如果你的表格很少的话可以使用这个自带的DataTable,如果表格很多且会频繁改动,那么每次改动后都要手动在UE编辑器中一个一个操作,所以,建议用C++动态加载*.csv:
FString csvFile = FPaths::GameContentDir() + "Downloads\\DownloadedFile.csv";
if (FPaths::FileExists(csvFile ))
{
FString FileContent;
//Read the csv file
FFileHelper::LoadFileToString(FileContent, *csvFile );
TArray<FString> problems = YourDataTable->CreateTableFromCSVString(FileContent);
if (problems.Num() > 0)
{
for (int32 ProbIdx = 0; ProbIdx < problems.Num(); ProbIdx++)
{
//Log the errors
}
}
else
{
//Updated Successfully
}
}
参考自:
https://answers.unrealengine.com/questions/156354/how-to-load-the-csv-datatable-dynamically.html