In this lesson, you will learn how to create an exact duplicate of a UObject at runtime by leveraging Unreal’s serialization system to perform a "deep copy."
Why Deep Copying Matters
When you assign one object pointer to another (e.g., ObjectA = ObjectB), you are only copying the memory address. Both pointers now look at the same object. If you change a variable in ObjectA, ObjectB changes too. Sometimes, you need a completely independent twin—a new object with the exact same data as the original. This is a "deep copy."
How FArchive Serialization Works
Unreal Engine’s reflection system (which we learned about in lessons 17-19) knows exactly what properties exist in your class. We can use a special type of FArchive to "stream" the data of an object into a memory buffer and then "stream" it back out into a brand-new object.
Think of it like taking a digital snapshot of an object and using that snapshot to build a fresh, identical clone.
Implementation Example
To perform this, we use FMemoryWriter and FMemoryReader. Here is how you can clone a UObject:
UObject* CloneObject(UObject* SourceObject)
{
if (!SourceObject) return nullptr;
// 1. Create a buffer to hold the serialized data
TArray<uint8> Data;
FMemoryWriter Writer(Data);
// 2. Serialize the source object into the buffer
SourceObject->Serialize(Writer);
// 3. Create a new, empty object of the same class
UObject* NewObject = NewObject<UObject>(GetTransientPackage(), SourceObject->GetClass());
// 4. Read the data back into the new object
FMemoryReader Reader(Data);
NewObject->Serialize(Reader);
return NewObject;
}
By passing the object through the Serialize function, we force it to write every UPROPERTY it owns into our Data array. When we read it back into the NewObject, the reflection system automatically maps that data to the new memory location. This ensures your clone is truly independent, allowing you to modify it without affecting the original.
Key Takeaway: Using FArchive serialization allows you to bypass simple pointer assignment and create a unique, independent copy of an object by capturing its internal state via the reflection system.