# How do you spawn a component from a class in UE4?

Background
I'm working on a shooter game at the moment and I'm trying to spawn an Actor Component for the weapon currently in use, in order to have less Actors to keep track of.
The problem with this is that I can't easily switch out components on the fly, without making a separate function for each weapon.

Question
Is there currently any way to spawn a component with blueprints from a class like you would do with an Actor?

Yes, you may spawn an actor component and attach it to any given actor. The C++ version of this would be:

UActorComponent* SpawnedComponent = ConstructObject<UActorComponent>(UStaticMeshComponent::StaticClass(), this, TEXT("DynamicSpawnedMeshCompoent");
if(SpawnedComponent)
{
SpawnedComponent->RegisterComponent();
SpawnedComponent->AttachTo(GetRootComponent(), NAME_None);
}


this is a pointer to an Actor class (so your weapon). Now, the key code here is the ConstructObject template function. In Blueprints you would call "Construct Object from Class" using a class reference to the Component you would like to create. The outer would be a reference to the owning actor of the component (the Weapon for instance). With the return value you will cast it to the desired component.

• I already know that it's possible to do in c++, but is it possible in blueprint? – Sturlen Jan 6 '16 at 16:28
• Follow the "Construct Object from Class" link it is the same thing as the C++ version of ConstructObject<> – Martin H Hollstein Jan 6 '16 at 17:42
• It just tested it and it just gives me "Error Wrong class to spawn" for both actors and components. Not sure what I'm doing wrong. – Sturlen Jan 7 '16 at 15:37
• Seems that this is a known issue. Here is the AnswerHub question related to this link. Finally, if you have some C++ skills, you can always use the above mentioned code and create a blueprint Library Function for yourself. – Martin H Hollstein Jan 7 '16 at 18:27