The order of Destroying components

Here I have 2 component, comp1 and comp2. and I attach comp2 to comp1 and set comp1 as comp2’s outer. Now I want to destroy both. should I destroy comp2 firstly? or the order is not necessary? Is it necessary to detach comp2 and then destroy?

The components are destroyed recursively when attached.

If you destroy the parent component it will automatically call destroy() on all children components before destroying itself.

If any of the children has children components they will be destroyed before it is destroyed.

Keep in mind that I’m talking about the built-in methods in Unreal. If you make your own method for destroying you should walk the hierarchy manually. (I strongly advice against custom object deletion in a system implementing Garbage Collector)

Also, the the built-in methods do not actually destroy the objects but just mark them for deletion by the Garbage Collector. This means that you can not really be sure if the components are actually deleted or when. Luckily isValid() returns false in both cases.

In the code, I find that it will not destroy component recursively, On the contrary, for its attached components, they will be promoted.

1 Like

I guess you were looking at

void USceneComponent::DestroyComponent(bool bPromoteChildren/*= false*/){...}

Promoting the children is an option which defaults to false.

On the other hand we have:

void USceneComponent::OnComponentDestroyed(bool bDestroyingHierarchy){...}

Destroying the hierarchy also seems to be optional…

I guess you can choose how you want to do the destroy action.

Anyway, whichever way you go, the components are detached automatically by the destroy function so you should not worry about manually detaching them.

you are right, I didn’t notice the hierarchy destroy function, Very thanks!