I’m trying to do a simple RTS demo game and for this I need spawning of actors. I want to create a template unit in the editor, add components and set values there and then be able to spawn (effectivly clone) this actor from the code resp. blueprints.
If I try to spawn an actor deriving from my custom “AEntity” actor class (no custom implementation there - just the stub) I can see that an actor gets spawned in the world outline and the first time I also see another entity being created, but when spawning more actors the old actor (the one used as the template) disappears.
Also I see that the spawned actor has a second PaperSprite render component.
This is the code for the spawning:
void ACustomGameMode::SpawnFromTemplate(AActor* pTemplate, FVector const& Location)
{
FActorSpawnParameters* params = new FActorSpawnParameters();
params->Template = pTemplate;
FRotator rot = FRotator(0.0f, 0.0f, 90.0f);
AActor* newActor = GetWorld()->SpawnActor(pTemplate->GetClass(), &Location, &rot, *params);
GetWorld()->AddNetworkActor(newActor);
// clone all components from template
{
TArray<UActorComponent*> components = pTemplate->GetComponents();
for (auto Itr(components.CreateIterator()); Itr; Itr++)
{
auto clazz = (*Itr)->GetClass();
UE_LOG(LogTemp, Warning, TEXT("Template-Component-Class: %s"), *clazz->GetName());
auto newComponent = newActor->CreateComponentFromTemplate((*Itr));
newComponent->RegisterComponent();
newActor->AddInstanceComponent(newComponent);
}
}
//newActor->InitializeComponents();
//newActor->AddToRoot();
//newActor->SetActorTickEnabled(true);
//newActor->SetTickGroup(ETickingGroup::TG_DuringPhysics);
//newActor->RegisterAllActorTickFunctions(true, true);
}
The commented lines show a few desperate tries to get this working
And this is the blueprint from the game mode where I spawn the new actors:
Any help is greatly appreciated!
EDIT:
Meanwhile I tried a few more things.
FActorSpawnParameters params;
params.Template = pTemplate;
params.bNoCollisionFail = true;
params.Owner = pTemplate->GetOwner();
FRotator rot = FRotator(0.0f, 0.0f, 90.0f);
AActor* newActor = GetWorld()->SpawnActor<AActor>(pTemplate->GetClass(), Location, rot, params);
Shorter cleaner code, but same problem. Obviously if your clone from a blueprint class you don’t have to clone the components manually, as they are inherited.
Still the old actor gets “removed” with this code.
FActorSpawnParameters params;
params.bNoCollisionFail = true;
params.Owner = pTemplate->GetOwner();
FRotator rot = FRotator(0.0f, 0.0f, 90.0f);
AActor* newActor = GetWorld()->SpawnActor<AActor>(pTemplate->GetClass(), Location, rot, params);
Doing a simple spawn without the template works as expected → adds an additional actor.