和《UE4基础:自定义GameInstance》的方法类似。和Godot不同的是UE4只能定义一个单例类,可以用它作为其它单例类的“根”
步骤
新建类
- 新建类
- C++实现
- 设置为GameSingleton
- 在C++中调用
- 在蓝图中调用
要继承于UObject
主要是实现一个获取实例的方法,这样就不用通过GEngine
获取完再类型转换了。 可以根据需要标记为蓝图可调用
//GameSingleton.h
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "UObject/ObjectMacros.h"
#include "GameSingleton.generated.h"
UCLASS(Blueprintable,BlueprintType)
class GAMECPP_API UGameSingleton : public UObject
{
GENERATED_BODY()
UFUNCTION(BlueprintCallable)
static UGameSingleton* GetInstance();
};
GameSingleton.cpp
#include "GameSingleton.h"
UGameSingleton* UGameSingleton::GetInstance()
{
if (GEngine)
{
UGameSingleton* Instance = Cast(GEngine->GameSingleton);
return Instance;
}
return nullptr;
}
设置为GameSingleton
UGameSingleton* GameSingleton = UGameSingleton::GetInstance();
在蓝图中调用