1.创建GameInstance C++类
2.在.h添加变量
class 工程名称_API UMyGameInstance : public UGameInstance
{
GENERATED_BODY()
public: //定义了三个公开的变量
UMyGameInstance();
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyGameInstance")
FString Name;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyGameInstance")
float Health;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyGameInstance")
int32 Age;
};
3.在.cpp初始化这三个变量值
#include "MyGameInstance.h"
UMyGameInstance::UMyGameInstance()
{
Name = TEXT("zhangsan");
Health = 198.4;
Age = 88;
}
4.接着在其他的文件编写
.h
#include "MyGameInstance.h" //引用MyGameInstance.h文件,才能引用到MMyGameInstance类里面的内容
UCLASS()
class 工程名称_API A工程名称+类名 : public A基类名
{
//新建一个MyGameInstance类型的指针变量,变量名称为:MyGameInstance
UPROPERTY()
UMyGameInstance *MyGameInstance;
}
.cpp
void A工程名称+类名::BeginPlay()
{
Super::BeginPlay();
MyGameInstance = Cast<UMyGameInstance>(GetWorld()->GetGameInstance());
if(MyGameInstance)
{
UE_LOG(LogTemp, Warning, TEXT("MyGameInstance is %s"), *MyGameInstance->GetName()); //注意这里打印的方法,有的带*号
UE_LOG(LogTemp,Warning, TEXT("MyGameInstance's Name is %s"), *MyGameInstance->Name);
UE_LOG(LogTemp,Warning, TEXT("MyGameInstance's Health is %f"), MyGameInstance->Health);
UE_LOG(LogTemp,Warning, TEXT("MyGameInstance's Age is %d"), MyGameInstance->Age);
}
}
5.设置GameInstance