YanDaik:
I made this function and it works fine:
//You pass to it class of component, otherwise it creates StaticMeshComponent
UActorComponent* UBlackMesaLifeBlueprintLibrary::AddComponent(AActor* a,USceneComponent *future_parent, FName name, UStaticMesh* mesh, UClass* NewComponentClass)
{
UActorComponent* retComponent = 0;
if (!NewComponentClass)
{
//DuplicateObject<UStaticMeshComponent>(dup_source,a,name)
UStaticMeshComponent* NewComponent = NewObject<UStaticMeshComponent>(a, name);// , EObjectFlags::RF_DefaultSubObject);
//UStaticMeshComponent* NewComponent = DuplicateObject<UStaticMeshComponent>(dup_source, a, name/*ActorCmp, NewActor, NewName*/);
//a->AddOwnedComponent(NewComponent);
FTransform CmpTransform;// = dup_source->GetComponentToWorld();
NewComponent->SetStaticMesh(mesh);
NewComponent->AttachToComponent(future_parent, FAttachmentTransformRules::KeepWorldTransform);
NewComponent->SetComponentToWorld(CmpTransform);
a->AddInstanceComponent(NewComponent);
NewComponent->OnComponentCreated();
NewComponent->RegisterComponent();
a->RerunConstructionScripts();
retComponent = NewComponent;
}
else {
UActorComponent* NewComponent = NewObject<UActorComponent>(a, NewComponentClass, name);
FTransform CmpTransform;// = dup_source->GetComponentToWorld();
//NewComponent->AttachToComponent(sc, FAttachmentTransformRules::KeepWorldTransform);
// Do Scene Attachment if this new Comnponent is a USceneComponent
if (USceneComponent* NewSceneComponent = Cast<USceneComponent>(NewComponent))
{
if(future_parent !=0)
NewSceneComponent->AttachToComponent(future_parent, FAttachmentTransformRules::KeepWorldTransform);
else
NewSceneComponent->AttachToComponent(a->GetRootComponent(), FAttachmentTransformRules::KeepWorldTransform);
NewSceneComponent->SetComponentToWorld(CmpTransform);
}
a->AddInstanceComponent(NewComponent);
NewComponent->OnComponentCreated();
NewComponent->RegisterComponent();
a->RerunConstructionScripts();
retComponent = NewComponent;
}
return retComponent;
}
Thanks for posting this YanDaik, just what I needed to get started with adding a component to an actor. I changed a few bits to suit my own needs but the overall idea works perfectly. I’m sure you probably know this, but if not, a small tip that maybe useful: instead of using UClass* as a parameter, use TSubclassOf<UActorComponent> . This will enforce that the class chosen will be derived from UActorComponent and will limit the choices available in Blueprint. Thanks again