Hey guys. I have a struct A that stores transform, softclass ptr, string, and TArray. I am using the ObjectAndNameAsStringProxyArchive. I am trying to save an array of struct A but can’t figure out how to. I have a struct B that holds the array and a string. Once all the struct A’s are added to the array in struct B, I want to save struct B to a file. Problem is I can’t figure out how to do this. I can save a single struct A by writing it’s TArray to file but that won’t work in the case of struct B. How would I save struct B to a file? (I already have a file path). I can provide more info if needed. Thank you in advance!
I figured it out. I needed to add a TArray to struct B to act as the bytestream. In struct B, I overloaded the << operator to save to my archive. And then to save, I just set the array, created a FMemoryWriter with the bytestream, and then created the archive and using the overloaded << operator, I saved to the archive. And finally, I wrote the bytestream to the file.
Hi! You can do this is several steps:
-
In all classes that you want to serialize or deserialize you should define << OPERATOR
USTRUCT(BlueprintType)
class SomeClass: public UObject {
GENERATED_BODY()… // All you props, for example Prop1, Prop2, etc
friend FArchive& operator<<(FArchive& Ar, SomeClass& objToSerialize) {
Ar << objToSerialize.Prop1;
Ar << objToSerialize.Prop2;
…
return Ar;
}
}; -
Saving data in file is simple as this
void Save(SomeClass& objToSave) {
FString filePath = FPaths::ProjectSavedDir() + "mydata.sav"; // file path you want FBufferArchive SaveData; SaveData << objToSave; FFileHelper::SaveArrayToFile(SaveData, *filePath); SaveData.FlushCache(); SaveData.Empty();
}
And some additional remarks:
- you can easily serialize and deserialize TArray if T is serializable in the sense of 1)
- serialize and deserialize in Unreal both are implemented with the same << OPERATOR. The thing is that some FArchive child classes save data and others - load. For example, FBufferArchive saves data from classes to stream (same as std::cout), while FMemoryReader can read data from stream to variables (same as std::cin)
- To serialize and deserialize class B that has class A prop, work it out with class A and after that you can start with class B
- UClass refs (TSubclassOf) can be serialized and deserialized by GetPathName() and StaticLoadClass(…) methods respectively
Sorry, but I forgot to tell that I figured it out an hour ago. I’ll post the answer shortly.