TExcelTAD
Home › Unreal Engine 5 with C++ › Weak & Soft Pointers, IsValid

Weak & Soft Pointers, IsValid

Not every reference should keep its target alive. "The last enemy that hit me", "the actor I'm currently looking at", "the target of my homing missile": if that actor is destroyed, the reference should quietly become empty. And some references point at assets you don't want loaded until needed. Unreal has a pointer type for each case.

Type Keeps alive? Points to Typical use
TObjectPtr<T> (with UPROPERTY) yes a loaded object owned components, data the object needs
TWeakObjectPtr<T> no a loaded object observers: targets, last attacker, UI watching a pawn
TSoftObjectPtr<T> no an asset by path, loaded or not big assets loaded on demand: a boss mesh, a level's music
TSoftClassPtr<T> no a class (Blueprint) by path spawn a Blueprint class that isn't loaded yet
TSubclassOf<T> yes (hard) a class "which pawn class to spawn"
TStrongObjectPtr<T> yes a loaded object holding UObjects from non-UObject code

TWeakObjectPtr

cpp
UPROPERTY()   // optional on a weak pointer; useful for editor visibility
TWeakObjectPtr<AActor> CurrentTarget;

void AArenaTurret::Aim()
{
    if (AActor* Target = CurrentTarget.Get())           // nullptr if it was destroyed or collected
    {
        const FVector ToTarget = Target->GetActorLocation() - GetActorLocation();
        SetActorRotation(ToTarget.Rotation());
    }
}

A weak pointer stores the object's index in the global object array plus a serial number. When an object dies, its slot's serial number changes, so a stale weak pointer can tell it no longer matches. That is the trick in the model below.

IsValid() vs a null check

cpp
if (Enemy)              { ... }   // only checks for nullptr
if (IsValid(Enemy))     { ... }   // nullptr check + "is it being destroyed / marked as garbage?"

A destroyed actor is not freed at once. After Destroy(), until the next GC pass, the pointer is non-null and points at an object marked as garbage (IsActorBeingDestroyed() is true). Calling gameplay functions on it is a classic bug: an enemy that already died gets "killed" again and awards double score. Use IsValid() for objects that can be destroyed (actors, components) and a plain null check for things that can't (a UDataAsset you loaded yourself). In Blueprints, the Is Valid node is the same check.

TSoftObjectPtr and asynchronous loading

A hard reference (TObjectPtr<USkeletalMesh>) in a Blueprint or class default loads the asset whenever the class loads. A boss with hard references to every attack's effects, sounds and meshes drags hundreds of megabytes into memory as soon as any level mentions the boss class. Soft references break that chain:

cpp
UPROPERTY(EditDefaultsOnly, Category = "Boss")
TSoftObjectPtr<USkeletalMesh> PhaseTwoMesh;

#include "Engine/AssetManager.h"
#include "Engine/StreamableManager.h"

void AArenaBoss::EnterPhaseTwo()
{
    if (PhaseTwoMesh.IsValid())                          // already loaded?
    {
        GetMesh()->SetSkeletalMesh(PhaseTwoMesh.Get());
        return;
    }
    // Load in the background, then continue.
    FStreamableManager& Streamable = UAssetManager::GetStreamableManager();
    Streamable.RequestAsyncLoad(PhaseTwoMesh.ToSoftObjectPath(),
        FStreamableDelegate::CreateWeakLambda(this, [this]()
        {
            GetMesh()->SetSkeletalMesh(PhaseTwoMesh.Get());
        }));
}

LoadSynchronous() also exists. It is fine in tools and loading screens and a hitch in gameplay. Use the Size Map and Reference Viewer (right-click an asset in the Content Browser) to find which hard references pull in what.

A runnable model: weak pointers with serial numbers

cpp · try it yourself
#include <iostream>
#include <string>
#include <vector>

struct Slot { std::string Name; int Serial = 0; bool Alive = false, Garbage = false; };
std::vector<Slot> Objects(2);

int Spawn(const std::string& name) {
    for (int i = 0; i < (int)Objects.size(); i++)
        if (!Objects[i].Alive) {
            Objects[i] = {name, Objects[i].Serial + 1, true, false};   // new serial for each new object
            return i;
        }
    return -1;
}

struct WeakPtr {
    int Index = -1, Serial = 0;
    static WeakPtr To(int i) { return {i, Objects[i].Serial}; }
    Slot* Get() const {
        if (Index < 0) return nullptr;
        Slot& s = Objects[Index];
        return (s.Alive && s.Serial == Serial) ? &s : nullptr;
    }
};

bool IsValid(Slot* s) { return s && !s->Garbage; }

void Report(const char* when, int raw, WeakPtr weak) {
    Slot* w = weak.Get();
    std::cout << when << ": raw -> " << Objects[raw].Name
              << ", weak -> " << (w ? w->Name : "null")
              << ", IsValid(weak) " << (IsValid(w) ? "true" : "false") << "\n";
}

int main() {
    int enemy = Spawn("Grunt_1");
    int raw = enemy;                          // AActor* Target
    WeakPtr weak = WeakPtr::To(enemy);        // TWeakObjectPtr<AActor> Target

    Report("alive", raw, weak);
    Objects[enemy].Garbage = true;            // Destroy(): marked, not freed yet
    Report("after Destroy()", raw, weak);
    Objects[enemy].Alive = false;             // the GC frees it
    Spawn("Grunt_2");                         // the slot is reused
    Report("after GC + respawn", raw, weak);
}
alive: raw -> Grunt_1, weak -> Grunt_1, IsValid(weak) true
after Destroy(): raw -> Grunt_1, weak -> Grunt_1, IsValid(weak) false
after GC + respawn: raw -> Grunt_2, weak -> null, IsValid(weak) false

Three lessons in one output: between Destroy() and GC only IsValid notices the actor is dead; after GC the weak pointer correctly says null; the raw pointer silently moved to Grunt_2.

Test yourself

What does IsValid(Actor) check that if (Actor) doesn't?

  1. Whether the actor is replicated
  2. Whether the object is being destroyed or marked as garbage
  3. Whether it has a mesh
  4. Whether it is visible

A homing missile tracks a target that may die mid-flight. Which pointer fits?

  1. TObjectPtr with UPROPERTY
  2. TWeakObjectPtr
  3. TSoftObjectPtr
  4. TSubclassOf

Why use a TSoftObjectPtr for a boss's phase-two mesh?

  1. It renders faster
  2. The mesh isn't loaded until requested, so referencing the boss class doesn't pull it into memory
  3. Soft pointers replicate
  4. It is required for skeletal meshes