Add component to actor in C++ (the final word!)

Thank you all, here is the summary (please reply if there are any issues with this and I will update!):

RUNTIME Best way:

  1. AActor::AddComponentByClass(), followed by AActor::FinishAddComponent() (only necessary if you specified true for bDeferredFinish)
    → This is what Blueprints use and does everything you need under the hood.
    → e.g. will do RegisterComponent() (if the component sets bAutoRegister, which is the default) and handle attachments (i.e. set as root, or attach to currrent root; otherwise manual attachment can be specified then handled yourself)

  2. MyActor->AddInstanceComponent(NewComp) should probably also be added, but seems to be used only to make any new components show up correctly in the editor

Constructor (CDO) Best way (the only way):

  1. CreateDefaultSubobject
    My only remaining question is if there are any caveats since this is in a CDO ( are there any restrictions to things that can be done here, obviously the game would not be running at this point but I would be curious to know if there are any rules somewhere on this, etc.)
21 Likes