How to extend serialization of a USTRUCT?

If I have a USTRUCT with some fields that cannot be UPROPERTY’s, how can I manually extend serialization and replication to notice these fields?

It seems easy for UCLASS, but I can’t find much information on how it’s done for USTRUCT.

You need to declare a special template in C++ to notify the engine of your custom serializer(s).
Something like this

USTRUCT()
struct FMyStruct
{
    GENERATED_BODY()

    int32 A;
    double B;

    bool Serialize(FArchive& Ar)
    {
        Ar << A;
        Ar << B;
        return true;
    }

    bool NetSerialize(FArchive& Ar, class UPackageMap*, bool& bOutSuccess)
    {
        // optimize for network (example)
        Ar << A;
        if (Ar.IsLoading())
        {
            float Temp;
            Ar << Temp;
            B = (double)Temp;
        }
        else
        {
            float Temp = (float)B;
            Ar << Temp;
        }
        bOutSuccess = true;
        return true;
    }
};

template<> struct TStructOpsTypeTraits<FMyStruct> : public TStructOpsTypeTraitsBase2<FMyStruct>
{
    enum
    {
        WithSerializer = true,
        WithNetSerializer = true,
        WithNetSharedSerialization = true,
    };
};

Look into the declaration of TStructOpsTypeTraitsBase2 for all possible flags.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.