Unreal Engine c++ Tutorial: Custom Net Serializers
Serialization
Serial means straight line… serializing data means converting all of your fancy structures to one, single, contiguous line of 1’s and 0’s. You can write bits to the network, or you can write them to your disk, but if you’re sending data somewhere, then you’re probably serializing it first.
Unreal Engine Replication
Unreal engine’s replication system works out of the box because of UHT; it’s like a second pre-processor pass that generates a bunch of useful code for you. Some of the code it generates serializes your data over the network. Instead of using generated serializers, we can write our own!
Writing a serializer offers flexibility with state replication that ISN’T supported natively by the engine, which lets us do some really cool stuff..
Hello Custom Net Serializer
Define a structure
Implement an insertion operator overload
Implement a NetSerialize function
(Optional) implement an insertion operator overload.
This is generally the operation for writing data to an archive. So, your structure will be easier to serialize from other structures and/or containers.
USTRUCT() struct FMyStruct { GENERATED_BODY() UPROPERTY() int32 Health; UPROPERTY() bool bIsDead; UPROPERTY(NotReplicated) TMap<FGuid, FMyStruct> OtherObjects; UPROPERTY() FVector_NetQuantize10 Position; // built‑in quantized vector type // this operator helps with serialization, but isn't necessary void operator<<(FArchive& Ar) { // pack Health into a variable‐length integer Ar.SerializeIntPacked(Health); // by default, booleans serialze at 32 bits, but this is only 1 Ar.SeralizeBits(bIsDead, 1); // FVector_NetQuantize10 implements its own NetSerialize Position.NetSerialize(Ar, Map, bOutSuccess); // Standard method for writing data to an archive Ar << OtherObjects; } /** * This is the one hook Unreal looks for when you ask for a custom serializer: * - return value is ignored * - set bOutSuccess = true on success */ bool NetSerialize(FArchive& Ar, UPackageMap* Map, bool& bOutSuccess) { Ar << *this; bOutSuccess = true; return true; } }; // Tell Unreal to use that NetSerialize() instead of the default memcpy one: template<> struct TStructOpsTypeTraits<FMyStruct> : public TStructOpsTypeTraitsBase2<FMyStruct> { enum { WithNetSerializer = true, // ← enable NetSerialize() }; };