Getting material instance from static mesh

I’m having a full on noob day.

I’m trying to get the material instance that has been applied to static mesh. The structure is Actor → Static Mesh Component → Static Mesh → Material. All I’m getting back is the default material assigned to the mesh in the content browser though:

    TArray <UStaticMeshComponent *> Components;
    Actor->GetComponents<UStaticMeshComponent>(Components);
    for (auto StaticMeshComponent : Components) {
        UStaticMesh * StaticMesh = StaticMeshComponent->StaticMesh;
        for (int x = 0; x < StaticMeshComponent->StaticMesh->Materials.Num(); ++x) {
            UMaterialInstanceDynamic * Material = UMaterialInstanceDynamic::Create(StaticMesh->GetMaterial(x), nullptr);
            UE_LOG(LogTemp, Warning, TEXT("Found material: %s"), *Material->GetName());
        }
    }

So I drag a default sphere into the scene, attach a material instance and then run the code and it always comes back with “DefaultMaterial” rather than the material instance I applied.

I’ve tested it with other meshes that have other materials assigned and it appears if you’ve manually assigned a material to the actor in the world you can’t get a reference to that material back.

What should I do to get the material applied to the mesh belonging to an actor?

I should have deleted this, it’s long since solved. Yes, was looking for it in the wrong place. :slight_smile:

Are you sure you applied the material to the Static Mesh? It sounds like you applied the material to the StaticMeshComponent, but you are looking for the material on the StaticMesh. I believe if you replace StaticMesh->GetMaterial(x) with StaticMeshComponent->GetMaterial(x), your code will find the material as intended.

Hopefully the next person who makes this mistake can find this answer then!