I am looking for a way to create and save a UStaticMesh in C++. What I want to achieve is to save an instance of UStaticMesh created with NewObject in C++ as Contents/MyStaticMesh. I tried the following, but it didn’t work. If anyone knows a solution, I would appreciate your guidance.
(UE 5.3)
UCLASS()
class MYPROJECT_API UMyEditorLibrary : public UEditorLevelLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "Nav")
static UStaticMesh* CreateTestMesh(UWorld* World)
{
UStaticMesh* Mesh = NewObject<UStaticMesh>();
// Create a new FStaticMeshSourceModel
FStaticMeshSourceModel& SourceModel = Mesh->AddSourceModel();
FMeshDescription* MeshDescription = new FMeshDescription();
TArray<FVector3f> Positions = { FVector3f::Zero(), FVector3f::One() * 100, FVector3f::XAxisVector * 100 };
for(auto i = 0; i < Positions.Num(); ++i)
{
auto P = Positions[i];
auto ID = MeshDescription->CreateVertex();
MeshDescription->GetVertexPosition(ID).Set(P.X, P.Y, P.Z);
}
// Copy the data from the FMeshDescription to the FStaticMeshSourceModel
SourceModel.GetMeshDescriptionBulkData()->SaveMeshDescription(*MeshDescription);
// Add the FStaticMeshSourceModel to the CombinedStaticMesh
//CombinedStaticMesh->AddSourceModel(*SourceModel);
// Build the CombinedStaticMesh
Mesh->Build(false);
FString AssetPath = TEXT("/Contents/TestStaticMesh");
auto& FileMan = FPlatformFileManager::Get();
auto& File = FileMan.GetPlatformFile();
auto res = File.CreateDirectoryTree(*AssetPath);
UPackage* Package = CreatePackage(*AssetPath);
Package->FullyLoad();
Mesh->Rename(TEXT("TestMesh"), Package);
FAssetRegistryModule::GetRegistry().AssetCreated(Mesh);
Package->MarkPackageDirty();
return Mesh;
}
};