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.

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");
    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.

| improve this answer | |
  • \$\begingroup\$ I already know that it's possible to do in c++, but is it possible in blueprint? \$\endgroup\$ – Sturlen Jan 6 '16 at 16:28
  • \$\begingroup\$ Follow the "Construct Object from Class" link it is the same thing as the C++ version of ConstructObject<> \$\endgroup\$ – Martin H Hollstein Jan 6 '16 at 17:42
  • \$\begingroup\$ 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. \$\endgroup\$ – Sturlen Jan 7 '16 at 15:37
  • \$\begingroup\$ 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. \$\endgroup\$ – Martin H Hollstein Jan 7 '16 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.