Using Save Game functionality with UObjects

I followed the documentation regarding Unreal’s built-in support for save games. I subclassed USaveGame and added some pointers to UObject-derived classes to be serialized. e.g.

class UDerivedSaveGame : public USaveGame
{
    GENERATED_BODY()
 public:
    UPROPERTY()
    UDerivedClass* Data1;

// more data

};

However, it doesn’t look like the data that Data1 points to is getting serialized. I have an array of FString’s in one of my UObject-derived classes, and I’d expect to see those strings if I opened the save file with a hex editor.

I was just wondering how to serialize the UObject-derived classes that the pointers point to. I appreciate any insight anyone may have!

After a bit of digging into engine code, I think I solved the problem (at least for my use case)!

Subclass the existing FMemoryWriter class and override the following operator as follows…

FArchive& FTraversingObjectWriter::operator<<(class UObject*& Res)
{
    FString ClassName = Res->GetClass()->GetName();
    (*this) << ClassName;

    Res->Serialize(*this);

    return *this;
}

FTraversingObjectWriter is the new class I wrote. This solution seems to work even if I reorder the properties in my class declaration. It also appears to work with arrays of UObject pointers.

I’ll leave the implementation of the inverse operation as an exercise to the reader. One can go about this by doing the following…

  1. Read the ClassName string and find the UClass associated with that ClassName.
  2. After that, instantiate a new UObject with the UClass you found with NewObject
  3. Deserialize your object.

I am sorry but I don’t get where and how to use this FMemoryWriter class

Or I just should to call it manually outside the SaveGame class ?

3 Likes