I am new to Unreal Engine 5 and I am in the process of writing a specific Blueprint code into C++, to achieve asynchronous spawning. So far, I’ve written the node to take a custom array, example below, and spawn the actor with the applied transformation.
[[RoomClass1, Location1, Rotation2],[RoomClass1, Location1, Rotation2]]
The node is shown below:
The code that cycles through the array:
AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [this, World, LatentInfo, SpawnDataArray, &OutSpawnedActors]()
{
TArray<AActor*> LocalSpawnedActors;
// Perform the actual spawning on the game thread
AsyncTask(ENamedThreads::GameThread, [this, World, LatentInfo, SpawnDataArray, &OutSpawnedActors, LocalSpawnedActors = MoveTemp(LocalSpawnedActors)]() mutable
{
for (const FRoomSpawnData& Data : SpawnDataArray)
{
if (Data.RoomClass)
{
FActorSpawnParameters SpawnParams;
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
AActor* SpawnedActor = World->SpawnActor<AActor>(Data.RoomClass, Data.Location, Data.Rotation, SpawnParams);
if (SpawnedActor)
{
LocalSpawnedActors.Add(SpawnedActor);
}
}
}
// Update SpawnedActors
SpawnedActors = MoveTemp(LocalSpawnedActors);
OutSpawnedActors = SpawnedActors; // Pass references back
OnCompleted.Broadcast(SpawnedActors); // Notify listeners
// Resume the latent action
if (LatentInfo.CallbackTarget)
{
FLatentActionManager& LatentManager = World->GetLatentActionManager();
auto* LatentAction = LatentManager.FindExistingAction<FAsyncBatchSpawnLatentAction>(LatentInfo.CallbackTarget, LatentInfo.UUID);
if (LatentAction)
{
LatentAction->OutSpawnedActors = SpawnedActors; // Update latent action output
}
}
});
});
Is there a real way to implement asynchronous spawning of actors? As currently each actor takes X amount of time to complete and it would be much better to spawn a few actors at the same time. The time it would take to initialize the world would be less.
Any help is appreciated!