Custom USTRUCT serialize functions

It’s possible to set up a custom Serialize function for USTRUCT types. Add a TStructOpsTypeTraits template for your struct like so:

USTRUCT(BlueprintType)
struct FMyStruct
{
	GENERATED_BODY()
 
	bool Serialize(FArchive& Ar);
};
 
template<>
struct TStructOpsTypeTraits<FMyStruct> : TStructOpsTypeTraitsBase2<FMyStruct>
{
	enum 
	{ 
		WithSerializer = true
	};
};

The Serialize function in the struct should return true if it was successfully serialized. Returning false makes it serialize using the default serialization.

If you have UPROPERTY(SaveGame) properties in your struct, you can use the default serialization for them. This avoids having to write serialization logic for fields which work with SaveGame:

UScriptStruct* Struct = StaticStruct();
 
if (Ar.IsLoading() || Ar.IsSaving())
{
	//This serializes all properties which have SaveGame
	Struct->SerializeTaggedProperties(Ar, (uint8*)this, Struct, nullptr);
	
	//Add your custom logic here
}

Manually serializing a specific struct

The following code serializes/deserializes MyStruct into Ar - it behaves effectively the same as Ar << SomeValue.

MyStruct.StaticStruct()->SerializeItem(Ar, &MyStruct, nullptr);

Note: Some engine builtin structs support <<, but other structs don’t. This is why you may need to use the method shown above.