Creating a custom component

I’m trying to create a custom component wich will have a static mesh.
This is my constructor:

	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	bWantsBeginPlay = true;
	PrimaryComponentTick.bCanEverTick = true;

	UStaticMeshComponent* MC= CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent"));

But the static mesh will not show. If I implement it in BeginPlay it works:

void UMyComponent::BeginPlay()

	UStaticMeshComponent* MC = NewObject<UStaticMeshComponent>(this);

But then it will not show in the editor…
How shall i do to create a mesh that is visible in the editor?

So you’re saying the component is there, but not the mesh for it?

From my experience, getting/setting meshes in C++ is messy - to the point that sometimes answers online don’t even work.

Try to use this for your SetStaticMesh:

SetStaticMesh(Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Game/PathToYourMesh"))))

Note that the /Game/ directory is the same thing as the upper-most directory in the content browser (In a template, this is where you’ll found Starter Content, Blueprint folders, etc.), or the MyProject/Content directory in the explorer.

I don’t think components can have other components as members. Use an actor if you need several components or, if all you need is a static mesh, let your custom component inherit from UStaticMeshComponent -> now you can use the mesh from inside your class.

Thanks for the help.
I don’t think setting the mesh is the problem and it’s hard to tell whether the component is there or not, since the component without the mesh is not visible :slight_smile:
Component can have other components as “members” since the example with BeginPlay works (which indicates that the component is there.)

I have ben experimenting with putting the code in OnRegister and it seams to work, but it needs a bit more testing before I can present the solution.

You should be able to see the component in the details panel:


Is it showing up at all? If so, when you select it, does it have anything set as the mesh, or is it still empty/none?