How can I procedurally add components?

I am trying to create an Actor which is composed of randomly selected/generated components at runtime.

The high level goal is to have a machine which will spawn an Actor each time you press a button which can have random properties. For exmaple they would look different by using different meshes and matierials, but also one may shoot, or move, or float, or have a light or particle effect.

The idea later on being that I could take 2 actors and based on some rules merge them together and exchange properties, like evolution/mutation.

I haven’t managed to find any way to add components in code that aren’t already declared at compile time, or construct components outside of the constructor because you need the PCIP. However in blueprint is it possible to add create and add components at runtime in the EventGraph.

How is this possible in code?

Hi Straits,

You can just use NewNamedObject<> with the Actor as an Outer parameter. What you can’t use is TSubobjectPtr<> to store the pointer to the newly created component inside of an actor and you should just use normal pointers, like so:

UPROPERTY()
UActorComponent* MyDynamicallySpawnedComponent;

or, store them inside of an array:

UPROPERTY()
TArray<UActorComponent*> MyDynamicallySpawnedComponents;

or just don’t bother because they should get added to AActor::OwnedComponents array (at least in latest version)