Download

Loading a model using C++.

I am posting this here to see if anyone would be able to help me out with a problem regarding loading a model into the editor, using C++. The idea is to have the model loaded and placed in the world, as soon as the project has started all from the code. I’ve watched a few videos on this and can’t seem to find any concise explanation as to how I would go about doing this. My model type is “.fbx”, I don’t know if that is relevant or not but it doesn’t work when I call the “.uasset” or “.fbx” version of the model.
Here is the .h file currently:



#pragma once

#include "GameFramework/Actor.h"
#include "ObjectLoader.generated.h"

UCLASS()
class OBJECTLOADING_API AObjectLoader : public AActor
{
	GENERATED_BODY()
		
public:	
	
	// Sets default values for this actor's properties
	AObjectLoader();

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;
	
	// Called every frame
	virtual void Tick( float DeltaSeconds ) override;
	UPROPERTY(EditAnywhere)
	UShapeComponent* Root;
	UPROPERTY(EditAnywhere)
	UStaticMeshComponent*  mesh;
	
};


The .cpp file currently:


// Fill out your copyright notice in the Description page of Project Settings.

#include "ObjectLoading.h"
#include "ObjectLoader.h"


// Sets default values
AObjectLoader::AObjectLoader()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	Root = CreateDefaultSubobject<UBoxComponent>(TEXT("Root"));
	RootComponent = Root;

	mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("mesh"));
	mesh->AttachTo(RootComponent);
	static ConstructorHelpers::FObjectFinder<UStaticMesh> ModelPath(TEXT("'Model1' /Content/Models/model1.uasset"));
	mesh->SetStaticMesh(ModelPath.Object);
}

// Called when the game starts or when spawned
void AObjectLoader::BeginPlay()
{
	Super::BeginPlay();


}
// Called every frame
void AObjectLoader::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );

}


Hello David,

your code is almost right except this line:

which should be:

StaticMesh is the type of UObject you try to load in this case UStaticMesh followed by the path and the asset name

The text you pass to FObjectFinder is called asset reference, you can get the reference by right clicking on the asset in the content browser -> copy reference

right click on asset -> context menu pops up -> copy reference

I hope that gets you started