Search code examples
c++unreal-engine4

How To Add The Value Of A Static Mesh Component From C++ Instead Of The Unreal Editor?


New to Unreal Engine here, but not new to c++. In the tutorials I saw, the way they created the UStaticMeshComponenent was by first using

mesh = CreateAbstractDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));

and then opening up the unreal editor and setting the shape of the mesh manually. For example, select the drop-down box and select "cube" or something. However, this seems a little inconvenient for me, since every time you drag and drop the actor into the level, you need to manually change the shape of the static mesh. I was wondering if it is possible set the shape from c++ itself. For example, something like this:

mesh->SetStaticMesh(Shapes::Cube);

Of course that isn't a real method, Shapes isn't a real namespace, and Cube isn't a real object. But what method and what parameters can I use to make this possible?


Solution

  • First you need to attach the component to your actor's root via: mesh->SetupAttachment(RootComponent);

    After that reference your static mesh. This is done via: const ConstructorHelpers::FObjectFinder<UStaticMesh> MeshObj(TEXT("/path/to/mesh"));

    Afterwards simply call UStaticMeshComponent::SetStaticMesh like this: mesh->SetStaticMesh(MeshObj.Object);