I have multiple static mesh files (in fbx format under %USERPROFILE%\Documents\models) imported to Unreal under Contents/MyMeshes. And they are stored with uasset extension. I was trying to load them with StaticLoadObject but always end up with nullptr.
Here is my code,
MyActorBuildings.h:
UCLASS()
class INSTANCEOBJECTS_API AMyActorBuildings : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor’s properties
AMyActorBuildings();
virtual void OnConstruction(const FTransform& Transform) override;
UFUNCTION(BlueprintCallable, Category = "Buildings")
TArray<FString> load_buildings();
UFUNCTION(BlueprintCallable, Category = "Buildings")
void populate_buildings(TArray<FString>& building_entries);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
MyActorBuildings.cpp:
void AMyActorBuildings::BeginPlay()
{
Super::BeginPlay();
TArray<FString> building_entries = load_buildings();
populate_buildings(building_entries);
}
void AMyActorBuildings::load_buildings()
{
TArray arr;
arr.Add(TEXT(“tower.uasset”));
arr.Add(TEXT(“powerline.uasset”));
return arr;
}
void AMyActorBuildings::populate_buildings(TArray& building_entries)
{
FString filepath;
FString assetpath = FPaths::ProjectContentDir();
assetpath.Append(“/MyMeshes/”);
for (int inst=0; inst < building_entries.Num(); inst++)
{
FString modelName = building_entries[inst];
filepath = assetpath;
filepath.Append(modelName);
UInstancedStaticMeshComponent* ism = NewObject<UInstancedStaticMeshComponent>(this, *modelName);
ism->RegisterComponent();
ism->SetFlags(RF_Transactional);
ism->SetMobility(EComponentMobility::Movable);
this->AddInstanceComponent(ism);;
UStaticMesh* meshToUse = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, *filepath, *filepath));
if (meshToUse != NULL) {
GEngine->AddOnScreenDebugMessage(-1, 60.f, FColor::Green, TEXT("loaded asset:") + filepath);
ism->SetStaticMesh(meshToUse);
} else {
GEngine->AddOnScreenDebugMessage(-1, 60.f, FColor::Red, TEXT("failed to load asset:") + filepath);
}
}
}