In this lesson, you will learn how to use TWeakObjectPtr to reference UObjects without preventing them from being cleaned up by the Garbage Collector.
The Problem with Strong References
When you use a standard pointer or a UPROPERTY() reference to a UObject, you create what we call a "strong reference." This tells Unreal’s Garbage Collector: "This object is still in use, so do not delete it."
However, in many gameplay scenarios, you might want to track an object—like a player’s target—without forcing it to stay alive. If the target is destroyed, a standard pointer would become a "dangling pointer," potentially causing your game to crash if you try to access it later.
Introducing TWeakObjectPtr
TWeakObjectPtr<T> is a specialized container that holds a reference to a UObject without preventing it from being destroyed. It acts like a "watchdog" for your object. If the Garbage Collector decides to destroy the object because no one else is holding a strong reference to it, the TWeakObjectPtr will automatically set itself to null.
How to use it
To use it, simply declare your variable using the template syntax. Before you access the object, you must verify it still exists using the .IsValid() method.
// In your header file
TWeakObjectPtr<AActor> MyTargetActor;
// In your source file
void AMyController::PerformAction()
{
// Always check if the object is still alive before using it
if (MyTargetActor.IsValid())
{
// Safe to access because we know it exists
MyTargetActor->Destroy();
}
else
{
UE_LOG(LogTemp, Warning, TEXT("The target was already destroyed!"));
}
}
Why use this instead of a raw pointer?
If you used a standard pointer, you would have no way to know if the object it points to has been deleted. By using TWeakObjectPtr, you gain a safe, reliable way to check the "liveness" of an object at any point in your code. This is essential for systems where objects are frequently spawned and destroyed, such as combat targets, temporary pickups, or AI goal markers.
Key Takeaway: Use TWeakObjectPtr to reference objects you don't own, ensuring you can gracefully handle cases where the object is destroyed by the Garbage Collector.