Why this code spawns two actors?

Hello. I am following the tutorials and, in the “on your own” chapter, I am wanted to learn how to attach complete actors to actors. I have managed to attach an actor to actor by spawning the actor I wanted to attach and attach its root component to the actor to be attached on. But the problem is, when this process is finished, I get two actors which I spawned instead of one.

Here is the code:

MyActor::MyActor() { // Constructor
// Spawn an actor and attach its root component to this actor
UWorld* ThisWorld = GetWorld();
	if (ThisWorld)
	{
		FActorSpawnParameters SpawnParameters;
		SpawnParameters.Owner = this;
		SpawnParameters.Instigator = Instigator;
		FVector SpawnLocation = GetActorLocation() + FVector(100.0f, 0.0f, 0.0f);

		AOrbitingActor* NewOrbitingActor = ThisWorld->SpawnActor<AOrbitingActor>(SpawnLocation, GetActorRotation(), SpawnParameters);
		NewOrbitingActor->AttachRootComponentTo(RootComponent);
	}
  }

I get the spawned actor attached to my actual actor, plus I get one another spawned actor which isn’t attached to anything. I don’t want this extra spawned actor. How can I prevent this? Is this a bug?

Make sure you also destroy the child when your actor is destroyed. When you drag a BP into the world, a preview object gets created, then deleted. The child remains, unattached to anything.

Do not use spawning actor inside constructors.
Try spawining in PostInitializeComponents()

I have tried but the editor crashed after I hit play.

And what about BeginPlay?

Constructor is more global action than starting game.
Spawning actors is gameplay event, so you can’t spawn any actors outside a game.

Yes, it’s mistake - PostInitializeComponents used for creating components, not actors. So to spawn actor you must use BeginPlay.
But there different nouances: actor will be spawn on server and on client and this actors will be differs, but will appear as one in current context. It should be considered.