How to deal with unique FNames for hierarchy of components?

I’m creating hierarchies of USceneComponents. I’m adding multiple versions of the same hierarchy of components to another component. It wasn’t working properly, it was adding way more components that it should have been and they weren’t parented properly. Then I realised that it worked properly as long as all the individual scene components have unique names.

So suppose I had an hierarchy of scene components like this:


If I’m adding a bunch of these to another component like this, it doesn’t work:

    PointRotator = CreateDefaultSubobject<USceneComponent>("Rotator");

    PointPlacer = CreateDefaultSubobject<USceneComponent>("Placer");

In order to make sure each component has a unique name, I have to do something like this:

FName RotatorName = FName(*(FString(GetOuter()->GetName() + "_" + this->GetName()) + "_Rotator"));
    PointRotator = CreateDefaultSubobject<USceneComponent>(RotatorName);

    FName PlacerName = FName(*(FString(GetOuter()->GetName() + "_" + this->GetName()) + "_Placer"));
    PointPlacer = CreateDefaultSubobject<USceneComponent>(PlacerName);

This seems rather cumbersome. Is there a better way to create a new object and easily ensure it has a unique name? Essentially just adding a number to the end, in the same way that adding a new component in the editor works?

I need something that works in the constructor (using CreateDefaultSubobject) and at runtime (using NewObject).

Try using the global function MakeUniqueObjectName. I believe the parameters are: Outer object (this in your example); Class of the object you’re naming (USceneComponent::StaticClass()); Optional name stub (“Rotator”).

That’s exactly it! I knew such a thing had to exist, but couldn’t find it by searching the documentation.