How to attach a camera component to a actor at runtime?

How do I make a CameraActor my main camera? - Pipeline & Plugins - Epic Developer Community Forums - setting camera.

https://docs.unrealengine.com/latest/INT/Programming/Assets/AsyncLoading/index.html - loading asset at run-time.

To attach actor/component to another actor/component you should call AActor::AttachRootComponent or USceneComponent::AttachTo

Hi guys,

I’d like to know how to attach a camera component to a actor dynamically. I know I can attach one using PCIP in the constructor, but can I attach a camera component at runtime outside the constructor? I think I need to register it after I attach it? Also, How to set the new attached camera as the main camera?

P.S. I think I don’t need to load a camera asset in this situation, but if I want to attach a mesh or something, how to load the asset at runtime?

Thank you!

Components are meant to be created only in constructor.

What are you trying to achieve exactly? Components must be initialized in constructor; game would crash or show error(not sure what exactly, forgot :frowning: ) if one of your subobjects is not initialized.

Just initialize all your components inside constructor, then, when required, simply call YourCamera->AttachTo(RootComponent) for example. There are various attaching functions available.

Thank you for your reply.
I think before using USceneComponent::AttachTo, I need to create component first, such as PCIP.CreateDefaultSubobject. It seems this PCIP.CreateDefaultSubobject function can only be called in the constructor. Is there any function that I can use to create components outside constructor?