Download

Why material can't be dynamically set in constructor?

Hi, so I had this:


AMusicalBlock::AMusicalBlock()
{
    StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>("BaseMeshComponent");
    auto MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Game/Meshes/musicalblock.musicalblock'"));

    if (MeshAsset.Succeeded())
    {
        StaticMesh->SetStaticMesh(MeshAsset.Object);
        StaticMesh->SetMaterial(0, DefaultMaterial);         //DefaultMaterial is a UMaterial object I have in my .h as UPROPERTY
    }

}


and it won’t work.

However if I put the ‘StaticMesh->SetMaterial(0, DefaultMaterial);’ in BeginPlay() instead, it works perfectly.

I’m curious about why is this (I was lucky I found this was my error in the answershub, couldn’t figure out how to set the material because it wasnt working in the constructor).

The constructor runs before uproperty initialization, so your material is not set yet.

Ah, didn’t know that, thanks.