How do you add components to an actor class at runtime in C++?

#Attach

You can create Static Mesh Actors and attach them to a core invisible actor that is the ships’ origin point


Then they will move, rotate, AND SCALE with the core component


so you just move around and scale the core actor, and all attached (at runtime) static mesh actors will follow just as you want


It’s easy!


#Attach, Actor.h

#Use EAttachLocation::KeepWorldPosition

/**
 * Attaches the RootComponent of this Actor to the RootComponent of the supplied actor, optionally at a named socket.
 * @param InParentActor				Actor to attach this actor's RootComponent to
 * @param InSocketName				Socket name to attach to, if any
 * @param AttachLocationType	Type of attachment, AbsoluteWorld to keep its world position, RelativeOffset to keep the object's relative offset and SnapTo to snap to the new parent.
 */

UFUNCTION(BlueprintCallable, meta=(FriendlyName = "AttachActorToActor", AttachLocationType="KeepRelativeOffset"), Category="Utilities|Orientation")

void AttachRootComponentToActor(AActor* InParentActor, FName InSocketName = NAME_None, EAttachLocation::Type AttachLocationType = EAttachLocation::KeepRelativeOffset);

#Set Static Mesh

Spawn your static mesh actor (AStaticMeshActor* MySMA)

if(!MySMA)return;
MySMA->StaticMeshComponent->SetStaticMesh(YourSMAsset)

#Dynamic Load Object

UStaticMesh* YourSMAsset = LoadedObjectFromFilePath

For rest of details see my wiki page

#Implementation

  • create lots of static mesh assets
  • create ONE blueprint of the static mesh actor class
  • spawn this blueprint at runtime
  • set the static mesh asset from file path for this spawned SMA

so you have

One Static Mesh Actor Blueprint = ShipPartBP
and looots of actual static mesh assets

and you attach the spawned Ship Parts to the invisible ship Core Actor

and then only move / rotate / scale the core ship actor

Rama