用GameInstanc保存全局数据,但是游戏关闭或者结束则消失
MyGameInstance.h
创建了三个数据myappid,myuserid,myname
UCLASS()
class CFIRST_API UMyGameInstance : public UGameInstance
{
GENERATED_BODY()
public:
UMyGameInstance();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyInstance")
FString MyAppID;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyInstance")
FString MyUserID;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyInstance")
FString MyName;
};
MyGameInstance.cpp
初始化三个变量
#include "MyGameInstance.h"
UMyGameInstance::UMyGameInstance()
{
MyAppID = TEXT("123");
MyUserID = TEXT("456");
MyName = TEXT("wangwu");
}
在其他文件头文件使用时需要引用
#include"MyGameInstance.h"
然后声明
UPROPERTY()
UMyGameInstance* MyInstance;
在cpp里实现
//转换为UMyGameInstance类
MyInstance = Cast<UMyGameInstance>(GetWorld()->GetFirstPlayerController()->GetGameInstance());
if (MyInstance)
{
UE_LOG(LogTemp, Warning, TEXT("MyInstance is %s"), *MyInstance->GetName());
UE_LOG(LogTemp, Warning, TEXT("MyAppID is %s"), *MyInstance->MyAppID);
UE_LOG(LogTemp, Warning, TEXT("MyUserID is %s"), *MyInstance->MyUserID);
UE_LOG(LogTemp, Warning, TEXT("MyName is %s"), *MyInstance->MyName);
}
然后在ue5中就可以设置
选择MyGameInstance
然后运行就能在输出日志里显示出内容
笔记总结来源于:【【虚幻5】UE5C++零基础全网全流程开发从入门到进阶教程合集(持续跟新中)】https://www.bilibili.com/video/BV1Dc411f7nx?vd_source=90cb1ac44856e5e826e2bee8aa9d8a41