Dynamically spawned UActorComponents disappear when parent is moved in editor

I have an Actor (a spaceship) that spawns its turrets dynamically at runtime. It uses the following code to do so, and works:

UChildActorComponent *child = NewObject<UChildActorComponent>(AttachedToPawn);

if (child)
{
	UObject *gCDO = itemClass->GeneratedClass->GetDefaultObject();

	child->ChildActorClass = TSubclassOf<AActor>(gCDO->GetClass());
	child->OnComponentCreated();
	child->AttachTo(AttachComponent, tmd->MountName);
	child->bCreatedByConstructionScript = true;
	child->RegisterComponent();

	ATurretActor *turret = Cast<ATurretActor>(child->ChildActor);

	turret->SetTurretData(tvd, GameData);
	turret->MountData = tmd;
	Turrets.Add(turret);
}

The bit with GetDefaultObject() is a bit messy, but I couldn’t find any way to convert a TSubclassOf(UObject) to TSubclassOf(AActor), which is the only thing ChildActorClass will accept.

Now - this code spawns the turrets and they attach to the right places and when the ship moves, they move with it. All working.

However, if I eject, grab the ship pawn and move it around manually (any amount) all of the dynamic turrets despawn. I have a UChildActorComponent that I added to the Ship manually in the ships blueprint, and it doesn’t despawn.

So there’s obviously something I am missing here. What is it?

1 Like

It’s because of this line :

child->bCreatedByConstructionScript = true;

Each time you will modify a value or move the actor around, all components created by the construction script (or flagged as so) will be destroyed. Usually that kind of behavior is wanted since you do the spawning in the OnConstruction() function and so it will respawn anyway.

If that’s not your case, you probably want to skip that line.

1 Like

Thanks, that’s got it and a good piece of info