Download

How to Add a Component to an Actor at Runtime?

I’m trying to add a USphereComponent to an Actor at runtime using the below code (which is derived from something else I found via google).



    USphereComponent* SpawnedComponent = ConstructObject<USphereComponent>(USphereComponent::StaticClass(), this, TEXT("DynamicSpawnedMeshCompoent"));
    if (SpawnedComponent)
    {
        SpawnedComponent->RegisterComponent();
    }


This dies at compile time, though. Is there some header I need to include to make this work? Is the implementation wrong?

VS throws the following errors:



Error    C2065    'ConstructObject': undeclared identifier
Error    C2275    'USphereComponent': illegal use of this type as an expression 


Thanks in advance.

Hi there! I am not sure ConstructObject is still supported.

What I am currently using to add components at runtime in UE 4.23 is something like this (called from the Actor to which the component is being added):




USphereComponent* SpawnedComponent = NewObject<USphereComponent>(this, "SphereComponent");

if (SpawnedComponent)
{
  //In case your component derives from USceneComponent, you can/should setup its attachment to the Actor's root
  SpawnedComponent->SetupAttachment(RootComponent);

  SpawnedComponent->RegisterComponent();
}



If you need to setup your RootComponent, here’s how I do that, in the Actor’s constructor:



RootComponent = CreateDefaultSubobject<USceneComponent>("Root");


I hope this helps! I am pretty sure there’s more complete information out there, but this it’s what’s working for me.