In this lesson, you will learn how to use TWeakObjectPtr to maintain a reference to a UObject without preventing the Garbage Collector from cleaning it up, effectively preventing crashes from dangling pointers.
The Problem: Dangling Pointers
In Unreal Engine, we often use raw pointers (AActor* MyActor) to reference objects. If that AActor is destroyed, the pointer still holds the old memory address. If you try to access MyActor after it has been deleted, your game will attempt to read memory that is no longer valid, causing a "dangling pointer" crash. While UPROPERTY() helps by nulling out pointers automatically, it only works for member variables. If you need a temporary reference or a way to track an object that might disappear, TWeakObjectPtr is your safety net.
How TWeakObjectPtr Works
A TWeakObjectPtr acts like a "safe" pointer. It keeps track of the object’s unique internal ID rather than just the memory address. When you try to access the object through the weak pointer, the engine performs a "check" to see if the object still exists in memory.
Here is how you implement it:
// 1. Declare the weak pointer
TWeakObjectPtr<AActor> TargetActor;
// 2. Assign it
TargetActor = SomeActorInstance;
// 3. Always check validity before using
if (TargetActor.IsValid())
{
// It is safe to use!
TargetActor->DoSomething();
}
else
{
// The object was garbage collected or destroyed
UE_LOG(LogTemp, Warning, TEXT("The actor is gone!"));
}
Why Use It?
Unlike a strong UPROPERTY reference, TWeakObjectPtr does not count toward the Garbage Collector’s "reachability" count. This means it won't keep an object alive just because you're pointing to it. It is perfect for systems like target markers, interaction handlers, or logging tools that need to know about an object if it exists, but don't need to force that object to stay in memory.
By calling .IsValid() or using the Get() method, you allow your code to gracefully handle the destruction of an object rather than crashing when the reference goes stale.
Key Takeaway: Use TWeakObjectPtr when you need to reference a UObject that may be destroyed, ensuring you can safely verify its existence before accessing it.