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.

1 Like

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
AControlPoint::AControlPoint()
{
 	// 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;
	SphereComponent->InitSphereRadius(400.f);

	StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Point"));
	StaticMesh->SetupAttachment(RootComponent);
	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'"));
BorderMesh->SetStaticMesh(plane_mesh.Object);
static ConstructorHelpers::FObjectFinder<UMaterial> plane_material(TEXT("Material'/Game/ClassicMansion/Materials/M_FlippedBorder.M_FlippedBorder'"));
BorderMesh->GetStaticMesh()->SetMaterial(0, plane_material.Object);