I am trying to spawn multiple actors at runtime and load meshes (uassets) from the content folder. I started to look at AsyncTask to do the job but I am struggling to get it to work. Any help would be greatly appreciated. This is the object class:
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnStaticMeshLoaded, UStaticMesh*, mesh);
UCLASS()
class AALTERMODULAR_API AOSMAsyncMeshObj : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AOSMAsyncMeshObj();
public:
UPROPERTY(EditAnywhere)
USceneComponent* Root;
UPROPERTY(EditAnywhere)
UStaticMeshComponent* Mesh;
UFUNCTION()
void Initialise(FString MeshPath);
UFUNCTION()
void SetObjMesh(UStaticMesh* mesh_);
And .cpp:
void AOSMAsyncMeshObj::Initialise(FString MeshPath)
{
FOnStaticMeshLoaded OnMeshLoaded;
OnMeshLoaded.AddDynamic(this, &AOSMAsyncMeshObj::SetObjMesh);
AsyncTask(ENamedThreads::AnyHiPriThreadHiPriTask, [OnMeshLoaded]()
{
TArray<UStaticMesh*> directoryMeshes = UaUtilities::GetMeshesFromDirectory("Assets/TwinmotionReadyposed/PosedHumans/meshes");
int32 index = FMath::RandRange((int32)0, (int32)directoryMeshes.Num() - 1);
OnMeshLoaded.Broadcast(directoryMeshes[index]);
});
}
void AOSMAsyncMeshObj::SetObjMesh(UStaticMesh* mesh_)
{
Mesh->SetStaticMesh(mesh_);
}
Currently the game is crashing with the following error:
Assertion failed: IsInGameThread() [File:D:\build++UE5\Sync\Engine\Source\Runtime\CoreUObject\Private\UObject\UObjectGlobals.cpp] [Line: 1549] Unable to load /Game/Assets/TwinmotionReadyposed/PosedHumans/meshes/SM_Child01. Objects and Packages can only be loaded from the game thread.
How to get asynchronous logic out of the GameThread then?