Why the static mesh is always a nullptr?

I created a static mesh in C++ and checked for nullptr, the mesh is always nullptr.

	UStaticMeshComponent* StaticMesh01;
StaticMesh01 = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh01"));
StaticMesh01->AttachToComponent(NewScene, FAttachmentTransformRules::KeepRelativeTransform);

always print not valid

You are creating the component but you still need to assign it a static mesh.

e.g.:

StaticMesh01 = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Box"));
StaticMesh01->SetupAttachment(RootComponent);

	ConstructorHelpers::FObjectFinder<UStaticMesh> MESH(TEXT("StaticMesh'/Engine/VREditor/BasicMeshes/SM_Cube_01.SM_Cube_01'"));
	if (MESH.Succeeded())
	{
		StaticMesh01->SetStaticMesh(Cast<UStaticMesh>(MESH.Object));
	}
2 Likes

so I am doing a stupid thing checking for a nullprt before assigning a mesh :smiley: , this is why it is always returning null? I was checking the availability of the meshcomponent if it is available to assign something to it.

if(Staticmesh01)
{
ConstructorHelpers::FObjectFinder<UStaticMesh> MESH(TEXT("StaticMesh'/Engine/VREditor/BasicMeshes/SM_Cube_01.SM_Cube_01'"));
	if (MESH.Succeeded())
	{
		StaticMesh01->SetStaticMesh(Cast<UStaticMesh>(MESH.Object));
	}
}

You need the constructor helper class, to find the mesh and a static mesh container for it, container is not the component, the component holds the container that has the mesh, the container think of it as the format for meshes once they are loaded on it to then be loaded onto the component.

you don’t need the if statements in this case.
you need two pointers for the container and component.

UStaticMesh* your_staticmesh_container_name
UStaticMeshComponent* Your_component_name

the constructer is formulated improper.
Give it a popper name instead of MESH choose Mesh_this or something, you may not know that “MESH” is actaually the mesh name for variable object.

You need the object variable to link it to the container
For example to link from the variable object of the constructor helper .
your_staticmesh_container_name = Your_Mesh_Variable_Object;

Then you need to set the pointer → on it as a component and use attachment function.

Like this:
Whatever your component name is->SetStaticMesh(your mesh container);

This can be done in many way, you can also use an attach to function, but this is usually used for the root component that you also have to set, it’s the last to set.

2 Likes