SpawnActor doesn't always work when in loop

I have an Actor that generates another actor every few seconds using the SpawnActor function. In most cases the function doesn’t spawn anything, but it didn’t use to do so. The timer is not the problem because I have a debug message that always shows when it has to.

void AObstacleGenerator::generate()
{
	if (Spawnable) {
		float gapPosition = (FMath::RandRange(-150, 150));
		AVerticalTile* VertTile = nullptr;
		VertTile = (AVerticalTile*)GetWorld()->SpawnActor<AVerticalTile>(Spawnable, FVector(GetActorLocation().X, GetActorLocation().Y, gapPosition), Rotation, SpawnInfo);
		
		if (VertTile != nullptr) {
			GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("Spawned an obstacle"));
		}

		VertTile->Init(Speed);

		GetWorldTimerManager().SetTimer(spawnHandle, this, &AObstacleGenerator::generate, SpawnTime, false);
	}
}

I can provide more code if needed

Hey @boisbois2 !

Looking at what you posted, can’t say for sure where the problem resides but there is something that you don’t need:

There is no need to c++ parse it to AVerticalTile* ((AVerticalTile*)), as that is already done automatically by the SpawnActor function

image

As you can see on the image, SpawnActor receives a class and returns a pointer of that same class.

// before
VertTile = (AVerticalTile*)GetWorld()->SpawnActor<AVerticalTile>(Spawnable, FVector(GetActorLocation().X, GetActorLocation().Y, gapPosition), Rotation, SpawnInfo);
// after
VertTile = GetWorld()->SpawnActor<AVerticalTile>(Spawnable, FVector(GetActorLocation().X, GetActorLocation().Y, gapPosition), Rotation, SpawnInfo);

If that doesn’t solve the issue, it might be that the function is called too many times, may I ask where are you calling it initially?

Edit: It might also be a problem with the class you are using, are you correctly assigning the variable Spawnable?

It might be a collision issue, try adding this to your SpawnInfo
SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;

Solved: I didn’t touch anything, the code just fixed itself after a few hours. I have no idea how that happens and I hate when Unreal does stuff like this.

it may not be fixed, hope it is but because the editor will keep stuff in memory between Play In Editor sessions, your loop may be able to spawn those actors. Once you close the editor or build a game it may not work.