Assign material to a mesh in C++ not working

Hi,
I try to assign a material to a mesh, but it doesnt work (no material visible). Here is my code :

.h
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
UMaterialInterface* TheMaterials;

.cpp
static ConstructorHelpers::FObjectFinder SphereVisualAsset(TEXT(“/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube”));
UStaticMeshComponent* SphereVisual = CreateDefaultSubobject(FName(*s));
SphereVisual->SetStaticMesh(SphereVisualAsset.Object);
SphereVisual->SetMaterial(0, TheMaterials);

I set TheMaterials in the editor and I can confirm it’s not NULL.

If you restart editor does the selected material apper?

Apart from restarting the editor have you tried to set it in OnConstruct?

The problem you’ve having here is that you’re using the constructor. The variable, in the constructor, IS null, unless you set it in the constructor (which you should, to null - you should always initialise variables.)

To fix your problem, you need to move the SetMaterial line to a different function. Override either PostInitProperties (which is run after bp props have been loaded, I believe) or PostInitializeComponents and set the material there. Or OnConstruct as somebody else said.

You probably want to add a UPROPERTY variable for your sphere, too, if you haven’t, so you can easily access it in the other method.

I’ll resolve the issue to keep track of it

THANK YOU, this is exactly what I was facing. For any future Googlers, this is relevant to everything, including assigning a StaticMesh to your StaticMeshComponent programmatically