C++ scene capture and MID not working

Dear experts,

I’ve read and followed a few posts here but still cannot get my code work.

I was spawning portal actors at runtime, and trying to have each spawned portal display a 2D scene capture. The scene capture component is located at the portal’s spawn point. Below is part of my code. What I’m seeing is still the default skin of the static mesh cube, instead of the scene captures. I must have missed something essential. Please enlighten me. Thanks!!

.h

// member of class AQLPortal
USceneCaptureComponent2D* PortalCamera;
UTextureRenderTarget2D* PortalRenderTarget;
UMaterialInstanceDynamic* PortalDynamicMaterial;
UMaterialInterface* PortalMaterialInterface;

.cpp

AQLPortal::AQLPortal()
{

    // initialize member StaticMeshComponent to a static mesh cube

    ...


    PortalCamera = CreateDefaultSubobject<USceneCaptureComponent2D>(TEXT("PortalCamera"));
    PortalCamera->bCaptureEveryFrame = true;
    PortalCamera->AttachToComponent(RootComponent, FAttachmentTransformRules::SnapToTargetIncludingScale);
    PortalRenderTarget = CreateDefaultSubobject<UTextureRenderTarget2D>(TEXT("PortalRenderTarget"));
    PortalRenderTarget->InitAutoFormat(1024, 1024);
    PortalRenderTarget->AddressX = TA_Wrap;
    PortalRenderTarget->AddressY = TA_Wrap;
    PortalCamera->TextureTarget = PortalRenderTarget;
}

void AQLPortal::BeginPlay()
{
    Super::BeginPlay();

    PortalCamera->UpdateContent();
    // PortalDynamicMaterial = UMaterialInstanceDynamic::Create(BluePortalMaterial, nullptr); does not produce captured scene either
    PortalDynamicMaterial = StaticMeshComponent->CreateAndSetMaterialInstanceDynamic(0);
    StaticMeshComponent->SetMaterial(0, PortalDynamicMaterial);
}

Answering my own question after many hours of testing.


The steps are:

UE

  • create a material asset and render
    target
  • create a texture sample as the input
    for the material and set the texture
    to render target
  • name the texture sample as
    PortalTexture

C++

  • import the material asset

  • create and set MID by. The crux is to make sure FName here matches the one you set in UE.

     PortalDynamicMaterial = StaticMeshComponent->CreateAndSetMaterialInstanceDynamicFromMaterial(0, PortalMaterial);
     PortalDynamicMaterial->SetTextureParameterValue("PortalTexture", PortalRenderTarget);
    
  • In passing there is no need to use SetMaterial()
    any more