Use Variable to set static mesh?

Is there a way to set a static mesh with a variable, something like

StaticMesh = StaticMesh’AssetReference’;

MeshComponent->SetStaticMesh(StaticMesh);

Trying to make simple things but the way I am doing it now seams overcomplicated.



ATestChopperPawn::ATestChopperPawn()
{
	// Structure to hold one-time initialization
	struct FConstructorStatics
	{
		ConstructorHelpers::FObjectFinderOptional<UStaticMesh> ChopperMesh;
		FConstructorStatics()
			: ChopperMesh(TEXT("/Game/Flying/Meshes/SM_Apache.SM_Apache"))
		{
		}
	};
	static FConstructorStatics ConstructorStatics;

	RootMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("RootMesh0"));
	RootMesh->SetStaticMesh(ConstructorStatics.ChopperMesh.Get());
	RootComponent = RootMesh;
}


Looks like you’re doing it right. The reason it’s not so straightforward is that what you want to happen in your line

will generally involve a dynamic asset load into memory.

I guess the process could be made a little more streamlined, but generally doing this isn’t recommended anyway. You are much better off just adding a static mesh pointer or asset reference property to your class, and selecting the mesh in the editor. Hard referencing an asset through C++ is best avoided.

the best way to do this is mark the variable StaticMesh as UPROPERTY(EditDefaultsOnly) then write rest of code assuming StaticMesh’s value is what you want it to be, then in the editor make a blueprint that is child of your C++ class and select the mesh you want to use in the blueprint’s window. its a much more simple and convenient way.

But in that case you should set the static mesh in either OnConstruction or BeginPlay function