How set something to a thing in the content browser?

I have a APawn class here being used to delegate events in the scene and it holds a reference to another AActor in the scene. I want to get the static mesh component from that actor and set its material.

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Refs")
AActor *actor;

void GameManager::InputEvent(){

    actor->GetStaticMeshComponent()->SetMaterial(0, SomeColor);
}

SomeColor is the name of the material in my content browser and I don’t know how to properly reference it in code to hand off to that parameter.

If you want the one who uses your editor to specify the material, then you should add it as a property in your pawn class

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="SomeCategory")
UMaterialInterface* SomeColor;

If you want to provide a default value for SomeColor then you can use FObjectFinder in the constructor.

If you don’t want the material to be always loaded you can use TAssetPtr instead of UMaterialInterface*, it’s just like TWeakObjectPtr but for asset.


The other solution is, provided that you have the path name to the material, you can use LoadObject, e.g:

 void GameManager::InputEvent(){
 	SomeColor = LoadObject<UMaterialInterface>(NULL, TEXT("/Game/Materials/M_ShinyRedVelvet.M_ShinyRedVelvet"));
 	if ( SomeColor )
 	{
 		actor->GetStaticMeshComponent()->SetMaterial(0, SomeColor);
 	}
 }

Hey Ghost,
You can get your StaticMeshComponent like this.

auto StaticMeshComponent = Cast<UStaticMeshComponent>(actor->GetComponentByClass(UStaticMeshComponent::StaticClass()));

if(StaticMeshComponent)
{
    StaticMeshComponent->SetMaterial(0, SomeMaterial);
}

I would recommend you to look into DynamicMaterialInstances
With them you can change the Values of Parameters in your Material.
For example:
you have a parameter “Color” in your Material which is defaultly blue.

If you create now a Dynamic Instance of you Material by:

UMaterialInstanceDynamic* MID = StaticMeshComponent->CreateDynamicMaterialInstance(0, StaticMeshComponent->GetMaterial(0));

//Change Color to Red
StaticMeshComponent->SetMaterial(0, MID);
					MID->SetVectorParameterValue(TEXT("Color"), FVector(1,0,0));

The best way to use Dynamic Material Instances, is, to store them as members in your class or by:

UMaterialInstanceDynamic* MID = Cast<UMaterialInstanceDynamic>(StaticMeshComponent->GetMaterial(0));

if(MID)
{
    //Change Parameter Values
}

Greetings :wink: