Getting material instance from staticmesh

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) {
                UMaterialInstance * Material = (UMaterialInstance *)StaticMesh->GetMaterial(x);
                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.

How should I be doing this?

Second question: are there any examples of how to use USceneCaptureComponent2D in C++? Right now I’m creating one with NewObject but it throws an exception and says that the ViewWidth is zero:


// Capture camera    CaptureCamera = NewObject<USceneCaptureComponent2D>(this, FName("CaptureCamera"), RF_Transient);
    CaptureCamera->bWantsInitializeComponent = true;
    CaptureCamera->RegisterComponent();
    CaptureCamera->InitializeComponent();
    CaptureCamera->CaptureSource = ESceneCaptureSource::SCS_SceneColorHDR;
    CaptureCamera->FOVAngle = 90;
    CaptureCamera->bCaptureEveryFrame = false;
    CaptureCamera->TextureTarget = CaptureTarget;
    FSceneViewStateInterface * View = CaptureCamera->GetViewState();
    CaptureCamera->SetRelativeLocationAndRotation(FVector(0, 0, 100), FQuat(FVector::RightVector, 1.5708f));
    this->SetActorLocation(FVector(0, 0, 100));
    CaptureCamera->Activate(true);

Edit: missing this:


CaptureTarget->InitAutoFormat(1024, 1024);

Gotta initialize that render target before using it.

Regarding the materials, you’re accessing the StaticMesh’ materials instead of the StaticMeshComponent’s. :slight_smile:



UMaterialInstance * Material = (UMaterialInstance *)StaticMesh->GetMaterial(x);


should be:



UMaterialInstance * Material = (UMaterialInstance *)StaticMeshComponent->GetMaterial(x);