How to change a static mesh's material in C++?

I have an Actor class with a SphereComponent and a StaticMeshComponent, and I wanted to change the Static Mesh’s material when something overlaps with the SphereComponent. I don’t have much experience with materials so I’m kinda stuck on this.

Simply SetMaterial:

Easiest way to get material is to make UMaterial* varables for each with UPROPERTY(EditAnywhere,Category=Something) and set them in editor, you can also GetMaterial to get current material of mesh

Alternativly you can make one material with parameters that changes it’s apperence

Here is example i find to change material parameters in C++:

I tried the SetMaterial approach and it didn’t work, I think it might be my Constructor here. PointNotCaptured being the UMaterial variable I made.

// Sets default values
 	// 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;
	SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("Root Component"));
	RootComponent = SphereComponent;

	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Point"));
	StaticMesh->SetMaterial(0, PointNotCaptured);

Wait nevermind, SetMaterial did work when I used it in a function. Though I am still confused why it didn’t work in the constructor.

I was having the same problem, when I called SetMaterial in the constructor nothing would happen. I figured out setting the material directly on the static mesh and not the static mesh component worked…

static ConstructorHelpers::FObjectFinder<UStaticMesh> plane_mesh(TEXT("StaticMesh'/Engine/BasicShapes/Plane.Plane'"));
static ConstructorHelpers::FObjectFinder<UMaterial> plane_material(TEXT("Material'/Game/ClassicMansion/Materials/M_FlippedBorder.M_FlippedBorder'"));
BorderMesh->GetStaticMesh()->SetMaterial(0, plane_material.Object);