Issue with SaveGame in GameInstance when switching levels

Hi,

I am having issues with SaveGame when it’s used in the GameInstance class. I used the tutorial here to save a player name:

https://docs.unrealengine.com/latest/INT/Gameplay/SaveGame/Code/

I create the save game instance in GameInstance, save the player name, and then create another save game instance to load the name. I then have a function in GameInstance which just prints the name to log from the loaded instance. It works when the game starts on the first level, but if I go to another level, and then try to call the same function to print the name from the GameInstance, it crashes. I recorded a video which should make it a little easier to understand. Please help :smiley:

You don’t want to place your game saves in persistent variables. You only want them to exist while you are retrieving data from them or writing data to them. There’s certainly no reason to keep multiple copies; you can use the same one to load and save the game if you want to have it persist for some reason.

Rather than storing the entire game save object, just copy the data you actually want to keep into persistent variables.

//MyGameInstance.h

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Player Data")
FString PlayerName;

UMyGameInstance();

virtual void Init() override;

UFUNCTION(BlueprintCallable, Category = "Game Saves")
bool SaveGame();

UFUNCTION(BlueprintCallable, Category = "Game Saves")
bool LoadGame();

UFUNCTION(BlueprintCallable, Category = "Game Saves")
void PrintPlayerName();


//MyGameInstance.cpp

UMyGameInstance::UMyGameInstance()
    :
    UGameInstance(),
    PlayerName(TEXT("Unloaded Player Name"))
{}

void UMyGameInstance::Init() {
    Super::Init();
    UE_LOG(LogTemp, Warning, TEXT("Game Instance Init"));
    if (!LoadGame()) {
        SaveGame();
        LoadGame();

    }

}

bool UMyGameInstance::SaveGame() {
    UMySaveGame* SaveGameInstance = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
if (SaveGameInstance) {
	SaveGameInstance->PlayerName = FString(TEXT("Loaded Player Name"));
	return UGameplayStatics::SaveGameToSlot(SaveGameInstance, SaveGameInstance->SaveSlotName, SaveGameInstance->UserIndex);

}
return false;
}

bool UMyGameInstance::LoadGame() {
    UMySaveGame* LoadGameInstance = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
    if (UGameplayStatics::DoesSaveGameExist(LoadGameInstance->SaveSlotName, LoadGameInstance->UserIndex)) {
        LoadGameInstance = Cast<UMySaveGame>(UGameplayStatics::LoadGameFromSlot(LoadGameInstance->SaveSlotName, LoadGameInstance->UserIndex));
        if (LoadGameInstance) {
            PlayerName = LoadGameInstance->PlayerName ;
            return true;

        }

    }
    return false;

}

void UMyGameInstance::PrintPlayerName() {
    UE_LOG(LogTemp, Error, TEXT("Player Name : %s"), *PlayerName);

}