Tarray in SaveGame instance is getting reset in every iteration ?

Hello Everyone,

I have class derived from “USaveGame” call “MetaData”, now this class is having Tarray of int’s.

In some other class i have method to save the data i want , which looks like this

void Importer::SaveGame() {
UMetaData* saveGameInstance = Cast<_UMetaData>
(UGameplayStatics::CreateSaveGameObject(UMetaData::StaticClass()));
saveGameInstance->meta_intArray.Push(2);
UGameplayStatics::SaveGameToSlot(saveGameInstance,TEXT(“MySlot”), 0); }

Now i ran this method first time, it created a file and saved array.I went out of this class.
Again i ran this method and saved the data. so now array size should be 2, right ?
But it is one !
Some how the new data over ride the old one ??
What am i missing ? can any one help me ??

Thanks in advance.

CreateSaveGameObject creates a new object, obviously, as the name suggests.

Meaning, it’ll have the default value of every value, so your array will be empty. You add one element to it => you’ll have one element.

If you want to add a new element to your array, then either:

  • You have to load the existing save game first, modify that, and save again
  • Or store the save game object, and instead of creating a new one, just keep pushing new values in its array, and save again

How can i do the Second option of “store the save game object, and instead of creating a new one, just keep pushing new values in its array, and save again” ?

can you give me the code snippet ?

I am trying to do the same in the above code !

Thanks @KristofMorva

Just create a member in one of your classes (like GameState): UMetaData* saveGameInstance;

And only create it once (like in BeginPlay, or on first save), and update save this one whenever you want (not a new object).

Even though, the correct solution would be not to use SaveGame for updating data. Whenever the user wants to save, you should fill the save object with the most recent data you want to save, run SaveGameToSlot, and you should forget it until the next game saving or loading.

If you’d like to use meta_intArray while playing, store it in GameState instead, and pass it to SaveGame only when saving.