I want to avoid that my Actor becomes a god class, therefore I encapsulate certain functionality into components. These components are added during runtime in PostInitializeComponents() since they have dependencies to other components which have to be set beforehand. I’ve used constructors but they are also called even before the game starts, which is unnecessary for me.
The best way I’ve found so far is to use OnRegister.
In AActor::PostInitializeComponents()
this->featureOne = NewObject<UMyFeatureOne>(this);
this->featureOne->RegisterComponent();
and putting the initialization code of the component into
void OnRegister() override;
Advantage of that is that once BeginPlay() is invoked at the parent Actor, also BeginPlay() on the registered component is called. [HR][/HR]
Are there better ways to add components to Actors (e.g. as UObjects or using UActorComponent::InitializeComponent() or …)? The requirements are:
- The component doesn’t need to have physics nor a visual representation in the game world.
- The components lifetime should be dependent on the Actors lifetime.
- The component is attached during runtime when certain conditions are met.
- The component should support replication.
- It doesn’t matter if it is visible in the editor or not.