Download

How to add an ActorComponent dynamically?

I’m making a system where I add different components to a building depending on the values I pass to it. I can’t figure out how to add these components and get them back when I need to reference them.

You could write a function that takes a pointer to the AActor you want to attach to, a UClass pointer for the component class you want attached to the actor, and an FString for the name you want to name the component. Something like:


UActorComponent* AttachComponentToActor(AActor* TheActor, UClass* TheComponent, const FString& ComponentName);

When you pass the component class to this function, it’ll be something like this:


UClassOfComponentYouWantToAttach::StaticClass()

Now, inside of this function, to make the component:


UActorComponent* NewComponent = NewObject<UActorComponent>(TheActor, TheComponent, FName(*ComponentName));

Then you can attach it to the actor, and return it as a UActorComponent* so you have a reference to it you can use later.

One more thing, if you want some idea of how you can attach it to the actor after creation, checkout SSCEditor::AddNewComponent from SSCEditor.cpp – you can do some similar code to what this function does.

You should not use the Blueprint functionality for creating an Actor Component at runtime. The correct way to create one is this:



UActorComponent* NewComponent = NewObject<UActorComponent>(TheActor, ComponentClass, NAME_None, RF_Transient);
check(NewComponent);

NewComponent->RegisterComponent();


If you do not register the component properly, numerous features will not work correctly.