UE5 文字游戏(2) C++实时读取CSV文件(游戏开始读取本地CSV剧本)

1.结构体代码

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

#pragma once

#include "CoreMinimal.h"
#include "Engine/DataTable.h"
#include "MyCharacterStats.generated.h"


USTRUCT(BlueprintType)
struct FMyCharacterStats : public FTableRowBase
{   
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    FString Name;

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    int32 Health;

    UPROPERTY(EditAnywhere, BlueprintReadWrite)
    int32 Attack;
};

2.写一个C++蓝图函数库

.h

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

#pragma once

#include "CoreMinimal.h"
#include "Misc/Paths.h"
#include "Serialization/Csv/CsvParser.h"
#include "Misc/FileHelper.h"
#include "MyCharacterStats.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "MyBlueprintFunctionLibrary.generated.h"

/**
 * 
 */
UCLASS()
class WEBH5_API UMyBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()
public:
	UFUNCTION(BlueprintCallable,Category="Data")
	static TArray<FMyCharacterStats> LoadCSVData(const FString& CSVFilePath);
	/*UDataTable* LoadCSVData(const FString& CSVFilePath, TArray<FMyCharacterStats>& DataTable);*/
};

.cpp 

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


#include "MyBlueprintFunctionLibrary.h"

TArray<FMyCharacterStats> UMyBlueprintFunctionLibrary::LoadCSVData(const FString& CSVFilePath)
{
	TArray<FMyCharacterStats> outStats;
	FString CSVContent;
	if(!FFileHelper::LoadFileToString(CSVContent,*CSVFilePath))
		return outStats;
	const FCsvParser Parser(CSVContent);
	const FCsvParser::FRows& Rows = Parser.GetRows();

	for (int32 RowIndex = 1; RowIndex < Rows.Num(); RowIndex++) {
		FMyCharacterStats TempStats;
		TempStats.Name = Rows[RowIndex][0];
		TempStats.Attack = FCString::Atoi(Rows[RowIndex][1]);
		TempStats.Health = FCString::Atoi(Rows[RowIndex][2]);

		outStats.Add(TempStats);
	}
	return outStats;
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值