MyActor.h
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = "Mesh")
class UStaticMeshComponent* StaticMesh;
//This is a quick function for getting mesh in case you put variables in private (I would suggest FORCEINLINE but that can get a bit different for new people but still take a look at those
UFUNCTION()
class UStaticMeshComponent* GetStaticMeshFromActor();
MyActor.cpp
#include "Materials/MaterialInterface.h"
#include "Components/StaticMeshComponent.h"
AMyActor::AMyActor()
{
//Constructor
StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh"));
SetRootComponent(StaticMesh);
}
//The Getter Function in case you made the Variable private/protected
UStaticMeshComponent* AApplyMaterialQuestion::GetStaticMeshFromActor()
{
return StaticMesh;
}
Now The Component
ChangeMaterialComponent.h
UPROPERTY(EditDefaultsOnly, Category = "Material")
class UMaterialInterface* NewMat;
ChangeMaterialComponent.cpp
#include "Materials/MaterialInterface.h"
#include "NewProject/MyActor.h"
#include "Components/StaticMeshComponent.h"
void UChangeMaterialComponent::BeginPlay()
{
Super::BeginPlay();
// ...
AMyActor* MeshofMyActor = Cast<AMyActor>(GetOwner());
if (MeshofMyActor)
{
UStaticMeshComponent* SMComp = MeshofMyActor->GetStaticMeshFromActor();
if (NewMat && SMComp)
{
SMComp->SetMaterial(0, NewMat);
}
}
}