How to spawn actors from another for Editor

Hello,

I am trying to make a simple wargame unit, unit should contains number of animated skeleton meshes with weapons etc. so it’s not only the one model, so I decide to use an actor for that. This Character actor should be used for main unit formation - 10 characters in 2 lines. Manually spawn this characters is a problem, so I decide to spawn them in unit actor OnConstruction()

void AGameSceneUnit::OnConstruction(const FTransform& Transform) 
{
	GenerateUnit();
}

// generate unit
bool AGameSceneUnit::GenerateUnit()
{
//	if(UnitCharacters.Num() != 0)
//		return true;

	FTransform initTranform;
	initTranform = FTransform::Identity;

	FActorSpawnParameters SpawnParameters;
	SpawnParameters.Owner = this;

	// formation is a component
	auto components = GetComponentsByClass(UGameSceneUnitSquad::StaticClass());
	for(auto& formation : components)
	{
		UGameSceneUnitSquad* squad = (UGameSceneUnitSquad*)formation;
		squad->InitFormation();
		UnitFormations.Push(squad);
	}

	if(UnitCharacterClass == nullptr)
	{
		UE_LOG(Wargame, Error, TEXT("AGameSceneUnit::GenerateUnit: no character class."));
		return false;
	}

	if(UnitFormations.Num() == 0)
	{
		UE_LOG(Wargame, Error, TEXT("AGameSceneUnit::GenerateUnit: no formations."));
		return false;
	}

	auto attachmentRule = FAttachmentTransformRules(EAttachmentRule::KeepRelative, EAttachmentRule::KeepRelative, EAttachmentRule::SnapToTarget, false);

	// create units
	for(int32 i = 0; i < UnitsNumMax; ++i)
	{
		FString name = GetName();
		name += "_";
		name += FString::FromInt(i);
		SpawnParameters.Name = *name;

		auto Character = ()->SpawnActor<AGameSceneUnitChar>(UnitCharacterClass, initTranform, SpawnParameters);
		Character->AttachToActor(this, attachmentRule);
		UnitCharacters.Push(Character);
	}
}

In result if I am not using
if(UnitCharacters.Num() != 0)
return true;

It generates lot of character actors attached and not to unit actor.

I also have add
// Called when destroys starts
void AGameSceneUnit::BeginDestroy()
{
for(auto character : UnitCharacters)
character->Destroy();

Super::BeginDestroy();

}
to check if it clears, in result I see that it deletes lot of actors too but not all of them

Question is how better to realize auto spawning of actors inside another actor not in gameplay (it’s easier) but also in Editor, because I want to see units on map edit if it’s possible.

I think best option for you is Actor Child Component, which let you attach actor like component and it should handle spawning for you

Other then that you could destroy old actor when new one is created in OnConstruction or use other events that AActor has in disposal

Looks like a solution, thank you! I’ll check this.

It helped but not 100% Instead of 1 character I still have 2, also on movement number of second UnitCharacter grow, I think it recreates it on transform. First UnitCharaster stays the same.

Been able to fix that, so it finally works well! My great gratitude!!!