I have made a UStruct like this:
USTRUCT(BlueprintType)
struct FTestLocation
{
GENERATED_BODY()
UPROPERTY()
int32 Value = 0;
UPROPERTY()
FTransform Transfrom;
UPROPERTY()
float Value2 = 0;
};
And I am trying to serialize/deserialize with a Buffer.
FBufferArchive SavingStream;
FTestLocation SaveLocation;
SaveLocation.Value = 1;
SaveLocation.Transfrom.SetLocation({2.f, 2.f, 2.f});
SaveLocation.Value2 = 3.f;
FTestLocation::StaticStruct()->SerializeBin(SavingStream, &SaveLocation);
FBufferReader LoadingStream(SavingStream.GetData(), SavingStream.Num(), false);
FTestLocation LoadLocation;
FTestLocation::StaticStruct()->SerializeBin(LoadingStream, &LoadLocation);
The issue is: after the Loading process,
LoadLocation.Value
is loaded correctly,
LoadLocation.Transfrom
is not updated at all.
LoadLocation.Value2
is clearly a trash value.
Can anyone let me know what I did wrong?
You can create a operator<< on the struct, which will serialize and deserialize easily from any archive.
In the struct, declare:
friend FArchive& operator<< (FArchive& Ar, FTestLocation& Struct);
Then, write an implementation in the global scope (so without namespace::), in the .cpp:
FArchive& operator<< (FArchive& Ar, FTestLocation& Struct) {
Ar << Struct.Value;
Ar << Struct.Transfrom;
Ar << Struct.Value2;
return Ar;
}
With this, any FArchive will correctly, in the same order, serialize and deserialize your struct to/from binary, just call SomeFArchive << MyFTestLocation
, thanks to the fact that almost all Unreal types, such as FTransform, FVector, etc. have the operator<< overloaded already. You don’t have to worry about their internal structure, sizeof, things like that at all.
Thanks for the reply, yes the solution you suggested could resolve my issue.
But what I am working on is a templated
solution using SerializeBin
to work on all the UStruct
, so Ideally I’d love to have something works without adding any new code.
Also, I am new to Unreal Engine, I am not sure if I am not using SerializeBin
correctly, or this is a bug on SerializeBin
? (I am going to dig into the implementation a bit later.)
Found the issue by debugging into the SerializeBin
implementation.
For the buffer Saved by FBufferArchive
since it’s FMemoryWriter
, I will need to use FMemoryReader
to load it.
Change
FBufferReader LoadingStream(SavingStream.GetData(), SavingStream.Num(), false);
To
FMemoryReader LoadingStream(SavingStream);
Would resolve the issue.