.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "InstancedSerializationSubsystem.generated.h"
UCLASS(DefaultToInstanced, EditInlineNew)
class UMyInstancedClass : public UObject
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, SaveGame, BlueprintReadWrite)
FString MyString;
UPROPERTY(EditAnywhere, SaveGame, BlueprintReadWrite)
float MyFloat;
};
UCLASS()
class UMySaveGame : public USaveGame
{
GENERATED_BODY()
public:
// Runtime object rebuilt from persisted fields after loading.
UPROPERTY(Transient, Instanced, EditAnywhere, BlueprintReadOnly)
UMyInstancedClass* MyClass;
};
UCLASS()
class INSTANCEDSERIALIZ_API UInstancedSerializationSubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
UFUNCTION(BlueprintCallable)
static UMySaveGame* LoadOrCreateArchiveBySaveGame();
};
.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "InstancedSerializationSubsystem.h"
#include "Kismet/GameplayStatics.h"
void UInstancedSerializationSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
Super::Initialize(Collection);
//Step 1:Load Or Create
auto Loaded = UInstancedSerializationSubsystem::LoadOrCreateArchiveBySaveGame();
if (!IsValid(Loaded->MyClass))
{
UE_LOG(LogTemp, Warning, TEXT("Failed to load MyClass from SaveGame!"));
}
//Setp 2 Write Data And Save
if (IsValid(Loaded->MyClass))
{
Loaded->MyClass->MyString = TEXT("Hello, Unreal!");
Loaded->MyClass->MyFloat = 6.28f;
UGameplayStatics::SaveGameToSlot(Loaded, TEXT("MySaveSlot"), 0);
}
}
UMySaveGame* UInstancedSerializationSubsystem::LoadOrCreateArchiveBySaveGame()
{
UMySaveGame* SaveGame = Cast<UMySaveGame>(UGameplayStatics::LoadGameFromSlot(TEXT("MySaveSlot"), 0));
if (!IsValid(SaveGame))
{
SaveGame = NewObject<UMySaveGame>(GetTransientPackage());
SaveGame->MyClass = NewObject<UMyInstancedClass>(SaveGame);
SaveGame->MyClass->MyString = TEXT("Hello, World!");
SaveGame->MyClass->MyFloat = 3.14f;
}
return SaveGame;
}

