这个流程很像 Godot中的 AutoLoad
步骤
自定义GameInstance类
- 自定义GameInstance类
- 设置项目的默认GameInstance类
- 实现获取这个GameInstance实例的方法
- 在C++中调用
- 在蓝图中调用
自定义GameInstance
类自然要继承自UGameInstance
基类
自动生成的
GameInstance
非常简单,并没有什么必须实现的方法。
//DemoGameInstance.h
#pragma once
#include "CoreMinimal.h"
#include "Engine/GameInstance.h"
#include "DemoGameInstance.generated.h"
UCLASS()
class GAMECPP_API UDemoGameInstance : public UGameInstance
{
GENERATED_BODY()
};
设置项目的默认GameInstance类
//DemoGameInstance.h
#pragma once
#include "CoreMinimal.h"
#include "Engine/GameInstance.h"
#include "DemoGameInstance.generated.h"
UCLASS(Blueprintable,BlueprintType)
class GAMECPP_API UDemoGameInstance : public UGameInstance
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable)
static UDemoGameInstance* GetInstance();
};
//DemoGameInstance.cpp
#include "DemoGameInstance.h"
UDemoGameInstance* UDemoGameInstance::GetInstance()
{
UDemoGameInstance* instance = nullptr;
if (GEngine)
{
FWorldContext* context = GEngine->GetWorldContextFromGameViewport(GEngine->GameViewport);
instance = Cast(context->OwningGameInstance);
}
return instance;
}
在C++中调用
UDemoGameInstance* GInstance = UDemoGameInstance::GetInstance();
在蓝图中调用
这样就无须通过 GameGameInstance
获取完再类型转换了。