Creating actors in runtime through code

I want a few cubes to spawn as soon as the game begins, so I used

GetWorld()->SpawnActor<ACube>(ACube::StaticClass(), Location, FRotator::ZeroRotator, ActorSpawnParams);

So I know this worked because I print some debug lines inside ACube::Tick… But the actor is not visible in the game.
In the constructor I initialized a box component like this:

BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("PyramidCube"));

So what am I missing?
Is there another component I need to add?
Do I need to do something else with the box component itself?

Ok, I got it to work… I was missing:


Now I see the cube’s wireframe. Which makes sense since I only added a mesh but no material.
Now the question is, can I create a simple plain red material and add it to the cube?
How do I do it?
I tried the following but didn’t work:

UMaterial* Material = NewObject<UMaterial>();
UMaterialExpressionConstant3Vector * BaseColorFactorNode = NewObject<UMaterialExpressionConstant3Vector>(Material);
BaseColorFactorNode->Constant = FColor::Red;
Material->BaseColor.Connect(0, BaseColorFactorNode);
BoxComponent->SetMaterial(0, Material);

Also tried adding more expressions but still does not work:

UMaterial* Material = NewObject<UMaterial>();

UMaterialExpressionConstant3Vector * BaseColorNode = NewObject<UMaterialExpressionConstant3Vector>(Material);
BaseColorNode->Constant = FColor::Red;
Material->BaseColor.Connect(0, BaseColorNode);

UMaterialExpressionConstant* MetallicNode = NewObject<UMaterialExpressionConstant>(Material);
MetallicNode->R = 1.0f;
Material->Metallic.Connect(0, MetallicNode);;

UMaterialExpressionConstant* SpecularNode = NewObject<UMaterialExpressionConstant>(Material);
SpecularNode->R = 1.0f;
Material->Specular.Connect(0, SpecularNode);;

UMaterialExpressionConstant* RoughnessNode = NewObject<UMaterialExpressionConstant>(Material);
RoughnessNode->R = 0.5f;
Material->Roughness.Connect(0, RoughnessNode);;

BoxComponent->SetMaterial(0, Material);

For basic things like this, google is your friend :wink:

Still not working… This is the code I used:


UMaterialInterface* Material;


UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(Material, this);
DynMaterial->SetVectorParameterValue("BaseColor", FLinearColor::Red);
BoxComponent->SetMaterial(0, DynMaterial);

I don’t think I am setting the actual base color of the material by setting the parameter “BaseColor”. Am I?

BTW, I cannot do this in the constructor (as the comment in the link suggests), I get an exception. I do it in the BeginPlay (as the code in the link suggests).
But still, I only see the cube’s wireframe.