In this lesson, you will learn how to use Child Actor Components to embed fully independent Actors inside other Actors, allowing you to create complex, modular hierarchies.
The Concept of Nesting
Up until now, you have used SceneComponents to build hierarchies. However, SceneComponents are just parts of a single Actor. Sometimes, you need a "parent" object to hold an entirely separate, fully functional Actor—like a modular turret system where the "Gun" is its own Actor class that can be swapped out, but is nested within the "Turret Base" Actor.
A Child Actor Component acts as a container. It doesn’t just hold geometry; it spawns an instance of an Actor class at runtime and manages its lifecycle. Because the child is a separate Actor, it maintains its own encapsulated logic, tick settings, and event graphs, separate from its parent.
Implementation
To use this, you add a UChildActorComponent to your parent class. You then specify the ChildActorClass you wish to spawn. Here is how you might declare one in your C++ header file:
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components")
UChildActorComponent* MountedWeapon;
In your constructor, you initialize it like any other component:
MountedWeapon = CreateDefaultSubobject<UChildActorComponent>(TEXT("MountedWeapon"));
RootComponent = MountedWeapon; // Or attach to an existing hierarchy
Why Use This?
The primary benefit is Encapsulation. If you have a vehicle and a driver, making the driver a Child Actor Component allows the driver to have its own collision, health, and behavior logic without cluttering the vehicle’s primary logic. You can change the ChildActorClass in the Editor without touching the parent’s code, making your system highly modular.
Remember, because the child is a full-blown Actor, you still need to ensure your parent-child communication is handled carefully (using pointers or casting) if they need to share data. You are essentially creating a "composition of Actors," which is a powerful way to build complex, reusable game systems.
Key Takeaway: Use Child Actor Components when you need to embed fully functional, independent Actor systems into a parent object to maintain clean, modular, and encapsulated code architecture.