I’m trying to load an OBJ file as a UStaticMesh at runtime in Unreal Engine using C++. How can I achieve this?
I have a C++ class RenderObject
that starts a process and generates an OBJ file. I want to import that OBJ file into Unreal Engine and add it to a specific location in the scene at run time.
Can I load the OBJ file directly into the class and add it to the scene at a specific location? If so, how can I achieve this?
Here’s the code I have so far:
// Called when the game starts or when spawned
void RenderObject::BeginPlay()
{
Super::BeginPlay();
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("__3D Object__ Loading"));
std::cout << "__3D Object__ Loading" << std::endl;
// Load the OBJ file as a UStaticMesh
FString ObjFilePath = "/testin_1_2.obj"; // Change this to the path of your OBJ file
UStaticMesh* StaticMesh = LoadObject<UStaticMesh>(nullptr, *ObjFilePath);
// Create a new StaticMeshActor
AStaticMeshActor* StaticMeshActor = GetWorld()->SpawnActor<AStaticMeshActor>();
// Set the static mesh of the StaticMeshActor
StaticMeshActor->GetStaticMeshComponent()->SetStaticMesh(StaticMesh);
// Set the location of the StaticMeshActor
FVector Location = FVector(1000.f, 915.f, 3.f); // Change this to the location you want
StaticMeshActor->SetActorLocation(Location);
}
I’m not sure if this is the correct way to achieve what I want. Can someone please guide me in the right direction?
Thanks in advance!