Change mesh's material on runtime in c++?

I have created character and teams and want to override their mesh’s material, but it seems to not work. Here’s code in shooter team game mode.

void AShooterTeamGameMode::RestartPlayer(AController* NewPlayer){

	UMaterialInstance* Mat;
	if (Teams[0]->PlayerIsInTeam(NewPlayer)){
		GEngine->AddOnScreenDebugMessage(-1, 10.0, FColor::White, TEXT("contains player"));
		if (NewPlayer->GetPawn() != NULL){
			GEngine->AddOnScreenDebugMessage(-1, 10.0, FColor::White, TEXT("has pawn"));
			ACharacter* Char = Cast<ACharacter>(NewPlayer->GetPawn());
			if (Char != NULL){
				GEngine->AddOnScreenDebugMessage(-1, 10.0, FColor::White, TEXT("has character"));
				Mat = Cast<UMaterialInstance>(StaticLoadObject(UMaterialInstance::StaticClass(), NULL, TEXT("MaterialInstanceConstant'/Game/Temp/Character/RedInstance.RedInstance'")));
				if (Mat != NULL){
					GEngine->AddOnScreenDebugMessage(-1, 10.0, FColor::White, TEXT("Material found"));
					USkeletalMeshComponent* Mesh = Char->GetMesh();
					if (Mesh != NULL){
						GEngine->AddOnScreenDebugMessage(-1, 10.0, FColor::White, TEXT("mesh found"));
						Mesh->SetMaterial(0, Mat);
						Mesh->SetMaterial(1, Mat);

When i run game in editor it logs all checkpoints, from “contains player” to “mesh found”, so SetColor should run and change material, but it doesn’t. The mesh’s main and only material is at index 0.
So how do i change material from outside of actor constructor?

We have a similar problem. We can only create dynamic materials in PostInitializeComponents

I am having a similar problem.

FString matPath = "Material'/Game/StarterContent/Materials/M_Metal_Gold.M_Metal_Gold'";
    	UMaterialInstanceConstant* material = Cast<UMaterialInstanceConstant>(StaticLoadObject(UMaterialInstanceConstant::StaticClass(), nullptr, *(matPath)));
    	if (material == NULL) {
    		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Material not found"));

it keeps printing “Material not found”.

This is a separate issue, due to a bad cast, and answered here

This code looks correct to me, so I feel like there’s something missing from the description of the issue. Try playing in editor, pausing the game, and looking at the materials assigned to the player’s skeletal mesh. What do you see?

Thanks! I fixed the problem!