If the actor is removed, then WeakPrt.IsValid() = false for all components

Hello.

I have an array containing pointers to an actor’s components:

TArray < TWeakObjectPtr< USceneComponent>> SelectedComponents;

If I remove an actor from the scene, will WeakPrt.IsValid() == false for all its components? For example:

SelectedComponents[index].IsValid() // always false ?

Hey @Babush61 how are you?

That’s right! If you remove/destroy the actor, “IsValid()” will return “false” for all of its components.

But there is an edge case where the garbage collector could be called after the “IsValid()” checks, resulting in “true” when it should be false!

A safe way to handle this could be:

// When iterating, always guard with IsValid()
for (int32 i = SelectedComponents.Num() - 1; i >= 0; --i)
{
    if (!SelectedComponents[i].IsValid())
    {
        SelectedComponents.RemoveAt(i); // clean up stale entries
        continue;
    }
    // safe to use .Get() here
    USceneComponent* Comp = SelectedComponents[i].Get();
}

Hope this helps you! Let me know if you need anything else!

Actor has ownership to its components. If actor is marked for destroy, so does its components. It’s by design that components cannot be created without an owner.

You may create an actor having a owner variable and behave like a component. If you need to access something after the owner is destroyed. BUT remember to do a cleanup for these component actors as their life time is different.