AActor* pActor= ....... pointer to my actor
UMyComponent* pComponent = NewObject<UMyComponent>(pActor);
pComponent->RegisterComponent();
Your code at line 4 spawns an actor, and does not add components to it.
SpawnActor also returns an actor, and not a component. It should afaik not compile.
Is there a way to do this if you don’t know the component type? For example, imagine you are given an array of the form
TArray& ComponentArray;
and you want to do something like create the component in ComponentArray[i]. Since you don’t know the specific component type, you can’t use NewObject. Also, I want to do this in a construction script so I can’t use spawn.
I have not done this myself, but I guess this should work:
As far as I know you can always get the type of an UCLASS by using the reflection-system-method MyObject::StaticClass().
So, if you do not know the type, you can always clone an unknown component by creating an UActorComponent and using the MyObject::StaticClass() of the source object.