I can not add Components to actor using code

I’m trying to add an UStaticMeshComponent to my Actor using visual studio.

.h

UStaticMeshComponent* Mesh;

.cpp

Mesh = CreateDefaultSubobject <“UstaticMeshComponent”> (“mesh”); // in the code UStaticMeshComponent is without " "


It works if i create a new project , but doesn’t if i try to add to my actual project. (it worked 2 days ago)

Do someone know if it’s a bug and in case how to fix it?

Use CreateDefaultSubobject only in the constructor

Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Write here the component name"));

It Works if i open a new project , but it doesn’t if i try to add it to my actual project. i think there is a problem with my actual project, maybe a file is corrupted.

What do you mean exactly by “it doesn’t work”, please be precise.

If the variable is set to null between the end of the constructor and the beginplay, I’ve seen it a lot, it can come from old blueprint serialized data that set your variable to null. You can try to change the variable name to fix this.

You are missing a second line that is required to attach your mesh to the component. You need to tell your mesh where it is attached to, otherwise it just exists within the confines of the class.

try something like the following:

Mesh->SetupAttachment( GetRootComponent() );

SetupAttachment is specific to SceneComponent and is useful for the hierarchy of transforms, but it is not mandatory. By default components will be children of the root component

Good to know but always good to be explicit with these things.