Dynamically spawned actors only spawn at origin

After roughly 6 hours of trial, error, and scouring the Internet for information, I have at last managed to complete the Herculean task of dynamically spawning an actor in UE4.

The only problem is that the SpawnActor<>() function ignores the location parameter and just spawns everything at the origin. I seem to be able to set the position of the actor after spawning. So what gives?

if( master && (tSpawn += DeltaTime) > 0.5f )
{		
	// reset spawn timer
	tSpawn = 0.0f;

	// spawn actor
	FVector pos( 100.0f,100.0f,100.0f );
	FRotator rot( 0.0f,0.0f,0.0f );
	FActorSpawnParameters sp;
	sp.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	sp.Owner = this;
	sp.Instigator = Instigator;
	auto pActor = GetWorld()->SpawnActor<AFloatingActor>( pos,rot,sp );

	// create static mesh, set mesh, and attach to root component
	auto statmesh = NewObject<UStaticMeshComponent>( pActor );
	statmesh->RegisterComponent();
	statmesh->SetStaticMesh( LoadObject<UStaticMesh>(
		pActor,TEXT( "/Engine/BasicShapes/Cylinder" ),nullptr,LOAD_None,nullptr ) );
	pActor->SetRootComponent( statmesh );
	pActor->SetActorLocation( FVector( dist( rng ),dist( rng ),dist( rng ) ) );
}

I am spawning the actors on the Tick() member function of the AFloatingActor (from one of the beginner tutorials) by the way. Commenting out the SetActorLocation() call sees every actor spawn at the origin, regardless of pos.

Another thing I found interesting is that, if I create a dummy root component and attach my static mesh component to that, statmesh->SetupAttachment( root ) crashes my editor window and triggers a breakpoint.

if( master && (tSpawn += DeltaTime) > 0.5f )
{	
	// reset spawn timer
	tSpawn = 0.0f;

	// spawn actor
	FVector pos( 100.0f,100.0f,100.0f );
	FRotator rot( 0.0f,0.0f,0.0f );
	FActorSpawnParameters sp;
	sp.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	sp.Owner = this;
	sp.Instigator = Instigator;
	auto pActor = GetWorld()->SpawnActor<AFloatingActor>( pos,rot,sp );

	// create root component and attach to actor
	auto root = NewObject<USceneComponent>( pActor );
	root->RegisterComponent();
	pActor->SetRootComponent( root );

	// create static mesh, set mesh, and attach to root component
	auto statmesh = NewObject<UStaticMeshComponent>( pActor );
	statmesh->RegisterComponent();
	statmesh->SetStaticMesh( LoadObject<UStaticMesh>(
		pActor,TEXT( "/Engine/BasicShapes/Cylinder" ),nullptr,LOAD_None,nullptr ) );
	statmesh->SetupAttachment( root );
	pActor->SetActorLocation( FVector( dist( rng ),dist( rng ),dist( rng ) ) );
}

It seems to me that if I’m going to want more than one component in the future, I’m going to need to be able to attach components to some root component. What am I missing here?

1 Like

Did you ever figure this out? I encounter this occasionally and it is a pain to always figure out and fix.

1 Like