First, the purpose
1. Think: Write a singleton in UE4
2. Thinking: Variables will not be reset when the scene is switched
Two, reference
1. UE4 basics: custom singleton class (Singleton Class)
https://orzgame.blog.csdn.net/article/details/106441788
- Summary: to be tested
2. (UE4 4.20) UE4's global singleton mode Singleton (variables are not GC when switching levels)
https://blog.csdn.net/qq_29523119/article/details/84801353
- Summary: to be tested
Three, operation: one:
1. Note:
- According to the instance created by this method, the UE4 breakpoint cannot be entered. If the variable is modified, it is really modified.
1. Create the C++ class of Object: MyGameSingleton
1. Project settings
1. Header file
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "Engine.h"
#include "UObject/ObjectMacros.h"
#include "MyGameSingleton.generated.h"
/**
*
*/
UCLASS(Blueprintable, BlueprintType)
class WQX_API UMyGameSingleton : public UObject
{
GENERATED_BODY()
UFUNCTION(BlueprintCallable, Category = "XZY")
static UMyGameSingleton* GetInstance();
};
1. Source file
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyGameSingleton.h"
//GameSingleton.cpp
//#include "GameSingleton.h"
UMyGameSingleton* UMyGameSingleton::GetInstance()
{
if (GEngine)
{
UMyGameSingleton* Instance = Cast<UMyGameSingleton>(GEngine->GameSingleton);
return Instance;
}
return nullptr;
}
1. Call in C++
UMyGameSingleton* GameSingleton = UMyGameSingleton::GetInstance();
1. Blueprint call
.
Three, operation: two: only blueprint
1. Create a new blueprint, GameInstance type
1. Base map & mode setting
1. Access the game singleton in the level blueprint