Newbie learning

Hi all, I’m a bit stuck trying to add a material to static mesh using an actor component class.

In begin play function I’ve tried the following.

UStaticmeshcomponent* objmesh = Cast<UStaticmeshcomponent>(GetOwner()) ;

//from the upropery umaterial in class

objmesh->setmaterial(0,mat);

This just crashes and my material pointer in not null.

I’m obviously applying it to the wrong object.

The Static Mesh Component is part of an Actor but you are Casting Directly to UStaticMeshComponent, The Owner Can’t be a StaticMesh in this Case but an Actor.
It should Cast To AActor then from that Actor you need to access its StaticMesh and Change its Material.

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);
        }
    }

}