UE5 c++自定义配置文件内容读取(c++编写、蓝图调用)
每个项目都会有一个需求,某些数据进行外部可配,基于此,在UE中用c++编写了自己常用的配置方案。
·
一、需求描述:
每个项目都会有一个需求,某些数据进行外部可配,基于此,在UE中用c++编写了自己常用的配置方案。
二、解决方案
配置文件展示:
#服务器IP
ip:127.0.0.1
name:名字
配置说明:
# 代表注释行
所有的配置以键值对的形式存储,以英文分号 : 隔开
.h脚本:
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyConfig.generated.h"
UCLASS()
class CONVERTEDITOR_API AMyConfig : public AActor
{
GENERATED_BODY()
public:
TMap<FString, FString> ConfigMap;
public:
// Sets default values for this actor's properties
AMyConfig();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void LoadConfigFile();
UFUNCTION(BlueprintCallable, Category = "Config")
FString GetValueForKey(const FString& Key);
};
.cpp脚本
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyConfig.h"
#include "Misc/FileHelper.h"
// Sets default values
AMyConfig::AMyConfig()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMyConfig::BeginPlay()
{
Super::BeginPlay();
LoadConfigFile();
}
// Called every frame
void AMyConfig::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMyConfig::LoadConfigFile()
{
FString ProjectDir = FPaths::ProjectDir();
FString ConfigFilePath = FPaths::Combine(ProjectDir, TEXT("netcfg.txt"));
FString FileContent;
if (FFileHelper::LoadFileToString(FileContent, *ConfigFilePath))
{
TArray<FString> Lines;
FileContent.ParseIntoArrayLines(Lines);
for (const FString& Line : Lines)
{
FString CurrentKey, Value;
if (Line.Split(TEXT(":"), &CurrentKey, &Value))
{
ConfigMap.Add(CurrentKey, Value);
}
}
}
}
FString AMyConfig::GetValueForKey(const FString& Key)
{
FString* ValuePtr = ConfigMap.Find(Key);
if (ValuePtr)
{
return *ValuePtr;
}
return FString();
}
使用方式:
在UE中基于MyConfig新建蓝图对象,将蓝图对象拖放到关卡中即可。
调用的时候通过调用GetValueForKey函数,传入key值,获取value。
注意事项:配置文件放到*.uproject文件同级。
更多推荐
所有评论(0)