Static mesh subcomponent in code, spawns at world center when placed

Hi!

I wanted to create a pickup item for my game similar to the “PizzaPickup” described in the programming introduction video, but having the UStaticMeshComponent already defined in my C++ class. So in the header file I defined the following property:

UPROPERTY(EditDefaultsOnly, VisibleDefaultsOnly, Category = Pickup)
TSubobjectPtr<UStaticMeshComponent> PickupMeshComponent;

And in the implementation constructor I did:

PickupMeshComponent = PCIP.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("PickupMesh"));

I did it this way because I wanted to have a blueprint with the mesh component already available, but with no mesh set. Also, i wanted to set a default offset of the mesh, slightly off the ground. Either way, with or without the offset, I launch the editor and create a blueprint based on my class. Setting a mesh in the component, and everything looks fine in the blueprint editor.

But once I place an instance of the blueprint in my scene, the bounding sphere gets placed correctly, but the mesh itself seems to spawn in the world center. No matter how many instances I place, the root (sphere) always ends up in the correct location, but the meshes are all bundled up in the same spot.

For now I’ve added the static mesh component via blueprint, and then it works fine. But I’d really like to have this in the code, so I can set some default behaviour for pickups, such as the mesh offset off the ground, and some pitch.

Any ideas? Am I doing something wrong?

And I should probably mention that moving the instance does NOT move its static mesh component, only the root component. I’ve tried setting the meshes relative location and all sorts of things in the code, but I keep getting the same issue.

Even though the components are created inside an actor object, you still need to attach them to have them inherit transforms. Try adding this:

PickupMeshComponent->AttachTo(RootComponent);

Ah, that makes perfect sense actually facepalm thank you!

This will not work unless you call it before you start operating on the component you’re attaching.

Did you set the Static Mesh Component as the Root Component?

RootComponent = PickupMeshComponent;

You can then set other components to the root as usual