Download

Problems spawning UStaticMeshComponents indirectly via a custom C++ class

[This could be a duplicate post but I couldn’t find my original attempt back]
Hi guys, I’m working on my first Unreal project, a level generator, with C++. My C++ is decent but my experience using it in Unreal is almost non-existant.
I have a problem where I can generate a set of UStaticMeshComponents from my LevelGenerator class (inherits from AActor) like this:


    for (size_t col = 0; col < _tilesArr.size(); col++)
    {
        for (size_t row = 0; row < _tilesArr[col].size(); row++)
        {
            if (_tilesArr[col][row]->_isFilled)
            {
                UStaticMeshComponent* Test = NewObject<UStaticMeshComponent>(UStaticMeshComponent::StaticClass());
                Test->SetStaticMesh(_pBasicBlock);
                Test->SetWorldLocation(FVector(col * 100, row * 100, 0));
                Test->RegisterComponentWithWorld(GetWorld());
                FAttachmentTransformRules rules = FAttachmentTransformRules(EAttachmentRule::SnapToTarget, false);
                Test->AttachToComponent(RootComponent,rules);
            }
        }
    }

However I want the generator to create a LevelBlockout (inherits from AActor) object that does that in stead, so I put the above code in a method of that class Generate() and call that from the generator. When I do it like this nothing happens in the level:


    _pLevelBlockout = NewObject<ALevelBlockout>();
    _pLevelBlockout->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, false));
    _pLevelBlockout->SetLayout(_pGrid->GetTiles());
    _pLevelBlockout->SetBasicBlock(_pBasicBlock);
    _pLevelBlockout->Generate();
 

I also tried casting it to an ActorComponent and using AddOwnedComponent() with no success.
I’m probably missing some insight in how Unreal C++ is supposed to be done here, but if anyone would be so kind to point me in the right direction that would be greatly appreciated!

[SOLVED]
I forgot to add the levelblockout actor itself to the world
_pLevelBlockout = GetWorld()->SpawnActor<ALevelBlockout>();

When creating Components by code you have to call MyComponent->RegisterComponent(); after you’re done.

If you create them in constructor then you must use CreateDefaultSubobject<>() instead of NewObject();

I was already using RegisterComponentWithWorld(), not sure what the difference is but the top code snippet already worked.

The issue was with the way I tried to spawn my LevelBlockout object, I’m still not sure what approach is the optimal one but I made it work with this:


_pLevelBlockout = GetWorld()->SpawnActor<ALevelBlockout>();