In this lesson, you will learn how to explicitly control the lifespan of your dynamic actors and components to ensure they persist exactly as long as your gameplay logic requires.
The Power of Ownership
In Unreal Engine, "Ownership" defines a hierarchical relationship: when an owner is destroyed, its owned objects are typically destroyed alongside it. Understanding this relationship is critical for memory management, as it prevents "zombie" objects—memory that is no longer needed but hasn't been cleaned up by the Garbage Collector yet.
When you spawn an Actor in C++ using GetWorld()->SpawnActor, that actor needs to know who "brought it into the world." By setting an Owner, you create a logical dependency. If you spawn an item attached to a player character, setting the player as the owner ensures that if the player is destroyed, the item doesn't linger in memory.
Managing References in Blueprints
A common challenge occurs when you store references to these spawned objects inside your Blueprints. If you spawn an object via C++ but don't properly manage its ownership, the Garbage Collector might identify the object as unreachable. If your Blueprint is still holding onto a reference, you risk a dangling pointer or a crash.
To keep things clean, use UPROPERTY() on your C++ pointers. This marks the object as "reachable" for the Garbage Collector, preventing it from being deleted while your code or Blueprint is still using it.
// In your C++ header
UPROPERTY()
AActor* MySpawnedObject;
// In your C++ source
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this; // Establish the ownership hierarchy
MySpawnedObject = GetWorld()->SpawnActor<AActor>(MyClass, Location, Rotation, SpawnParams);
By assigning the Owner in SpawnParams, you tell the engine, "This object belongs to me." If you then use MySpawnedObject->Destroy() when you are finished, the engine handles the cleanup gracefully. Keeping this ownership chain intact ensures that your memory footprint stays lean and your Blueprint references remain valid during the object's entire active lifecycle.
Key Takeaway: Establishing a clear Owner during spawning creates a parent-child lifecycle, while UPROPERTY() ensures the Garbage Collector respects your active references.