UE4 C++ 用SaveGame类写一个异步加载关卡
时间: 2024-03-10 07:51:04 浏览: 161
首先,你需要创建一个继承自`USaveGame`的保存游戏数据的类,并在其中定义需要保存的数据成员。接下来,你需要在异步加载关卡时加载这些数据。
以下是一个简单的示例:
```c++
// MySaveGame.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "MySaveGame.generated.h"
UCLASS()
class UMySaveGame : public USaveGame
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite)
FString LevelName;
};
// MyLevelLoader.h
#pragma once
#include "CoreMinimal.h"
#include "Engine/LevelStreamingDynamic.h"
#include "MySaveGame.h"
#include "MyLevelLoader.generated.h"
UCLASS()
class AMyLevelLoader : public AActor
{
GENERATED_BODY()
public:
AMyLevelLoader();
UFUNCTION(BlueprintCallable)
void LoadLevelAsync(const FString& LevelName);
void LoadLevelAsync_Internal(const FString& LevelName);
UFUNCTION()
void OnLevelLoaded();
private:
UPROPERTY()
ULevelStreamingDynamic* StreamingLevel;
UPROPERTY()
UMySaveGame* SaveGame;
};
// MyLevelLoader.cpp
#include "MyLevelLoader.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/World.h"
AMyLevelLoader::AMyLevelLoader()
{
PrimaryActorTick.bCanEverTick = false;
StreamingLevel = NewObject<ULevelStreamingDynamic>(this, ULevelStreamingDynamic::StaticClass());
StreamingLevel->bShouldBeLoaded = false;
StreamingLevel->bShouldBeVisible = false;
}
void AMyLevelLoader::LoadLevelAsync(const FString& LevelName)
{
SaveGame = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
if (SaveGame != nullptr)
{
SaveGame->LevelName = LevelName;
SaveGame->SaveAsync(0);
}
FStreamableManager& Streamable = UAssetManager::GetStreamableManager();
Streamable.RequestLevel(StreamingLevel->GetWorldAssetPackageFName(LevelName), FStreamableDelegate::CreateUObject(this, &AMyLevelLoader::LoadLevelAsync_Internal, LevelName));
}
void AMyLevelLoader::LoadLevelAsync_Internal(const FString& LevelName)
{
StreamingLevel->SetWorldAssetByPackageName(LevelName);
StreamingLevel->bShouldBeLoaded = true;
UWorld* World = GetWorld();
if (World != nullptr)
{
StreamingLevel->LevelColor = FColor::MakeRandomColor();
StreamingLevel->LevelTransform = FTransform(FRotator::ZeroRotator, FVector(0.f, 0.f, 0.f), FVector(1.f, 1.f, 1.f));
World->AddLevelStreamingActor(StreamingLevel, GetActorTransform());
}
}
void AMyLevelLoader::OnLevelLoaded()
{
if (SaveGame != nullptr)
{
FString LevelName = SaveGame->LevelName;
SaveGame->Delete();
SaveGame = nullptr;
// Do something with the loaded level...
}
}
```
在上面的示例中,`UMySaveGame`保存了需要在异步加载关卡时加载的数据成员。`AMyLevelLoader`是一个继承自`AActor`的类,它有一个`LoadLevelAsync`函数,它会异步加载指定名称的关卡,并在加载完成后调用`OnLevelLoaded`函数。在`LoadLevelAsync_Internal`函数中,我们使用`ULevelStreamingDynamic`类来加载关卡,并在加载完成后将其添加到世界中。在`OnLevelLoaded`函数中,我们可以获取保存在`UMySaveGame`对象中的数据成员,并进行后续操作。
请注意,以上示例仅用于演示目的,实际使用时可能需要进行更多的错误处理和数据验证。
阅读全文